+ 1
what's python @classmethod? please give me example
7 ответов
+ 9
Without @staticmethod, the method can't be called from inside the class or from an instance of the class because the reference to self is missing:
c = Calculator()
print(c.multiplyNums(5, 6)) # won't work without @staticmethod
+ 9
It is mostly used as another way to instantiate an object, instead of using the __init__ method (perhaps with a different parameter setting).
It is well explained in the link that Lothar provided -- there the class method new_square is used with just one parameter, and what it does it calls the regular __init__ underneath, passing the value of the single argument as respective two arguments required by __init__
+ 5
Using the descriptor @staticmethod is more or less a question of style. I am not aware of any worthwhile consequences when you leave it out.
+ 5
Anna Didn't notice that. I prefer putting (utility) functions into separate modules and not to group them in classes. Can you give me an example where you would want to use a staticmethod instead of an instance method (if you want to call it from the instance)?
+ 5
Thoq! I can't think of a situation where I would use a static method for other purposes than using the class as a namespace. For example a class "Name" could have a static method "validate(name)" that returns True if "name" is a valid name. The method could be called from __init__(self, name) in order to only allow valid names as input. And it could be called from outside the class, without actually creating an instance of the class, if you wanted to check if a string is a valid name (Name.validate(string)). I think that's the same as what you're describing.
+ 4
You can find more by reading this tutorial:
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2473/
+ 1
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's difference between this two codes, other than that the results are same and what does @staticmode do?