-3

I have 2 different code but they both work why?

class Calculator:
    def multiplyNums(x, y):
        return x + y
print('Product:', Calculator.multiplyNums(15, 110))

and

class Calculator:
    @staticmethod
    def multiplyNums(x, y):
        return x + y
print('Product:', Calculator.multiplyNums(15, 110))

what does @staticmethod?

kkwebba
  • 39
  • 1
  • 9

2 Answers2

2

You can see what is the effect of the @staticmethod decorator by doing:

cc = Calculator()
print(cc.multiplyNums(10, 2))

Without @staticmethod, the above code gives you an error:

TypeError: multiplyNums() takes 2 positional arguments but 3 were given

because you are implicitly passing cc as argument to the method (the self argument that you usually see as the first argument in method definitions, which in this case is not present).

With the @staticmethod decorator, it works, and prints 12.

Basically the decorator allows you to call methods without the self argument from class instances.

Valentino
  • 7,291
  • 6
  • 18
  • 34
-2

I have just edited your 1st method to make it instance method

 class Calculator:
 def multiplyNums(self,x, y):
    return x + y
 print('Product:', Calculator().multiplyNums(15, 110))

class Calculator:
@staticmethod
def multiplyNums(x, y):
    return x + y
print('Product:', Calculator.multiplyNums(15, 110))

So static method can neither modify object state nor class state. Static methods are restricted in what data they can access - and they’re primarily a way to namespace your methods.

Learner
  • 11
  • 1
  • 8
  • Hello! While the link may provide an anwers, link-only solution are discouraged. Please add some details in the question. – Valentino May 14 '19 at 18:29
  • What's difference between this two codes, other than that the results are same and what does @staticmode do? – kkwebba May 14 '19 at 18:35