Python 2.7 [PY27_Test Env]
Python 3.6 [PY36 Env]

Static Methods / Methods Only Class

In other object oriented languages, the concept is that static methods operate at the class level, do not have to be instantiated, and are the preferred approach to creating a class that houses nothing but one or more related methods (functions). In Python 3 (tested in Python 3.6), the code syntax seems to support this. In Python 2.7, the syntax seems to require intantiation of one instance to call into the "static method call". Below code illustrates how to make this owrk under Python 2.7 and Python 3.6 (which should work in Python 3.x in general).


In [1]:
# the object for this example was an answer to a problem first encountered on www.hackerrank.com

class Calculator:
    def power(self, n, p):
        if n < 0 or p < 0:
            raise ValueError("n and p should be non-negative")
        else:
            return n**p

In [7]:
if hasattr(__builtins__, 'raw_input'):
    input = raw_input
    
# Python 3.x:  input()
# Python 2.7:  raw_input()
# above line imports Python 3.x input() to Python 2.7 to make this code work in both places

myCalculator=Calculator()
T=int(input("Input Number of Tests: "))          
for i in range(T):
    n,p = map(int, input("Input 'n p' where n = number and p=power: ").split())
    try:
        ans=myCalculator.power(n,p)
        print(ans)
    except Exception as e:
        print(e)


Input Number of Tests: 2
Input 'n p' where n = number and p=power: 4 5
1024
Input 'n p' where n = number and p=power: 9 3
729

In [3]:
# works in Python 3.6
Calculator.power(Calculator, 3, 7)


Out[3]:
2187

In [5]:
# works in Python 2.7 ... includes 3.6 only code to show the error:
try:
    print(Calculator.power(Calculator, 3, 7))
    
except Exception as ee:
    print("Error: %s" %ee)
    print("Using Python 2.7 alternate code:")
    workingCalculator = Calculator()
    print(Calculator.power(workingCalculator, 3, 7))


Error: unbound method power() must be called with Calculator instance as first argument (got classobj instance instead)
Using Python 2.7 alternate code:
2187

In [ ]: