what's python @classmethod? please give me example | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

what's python @classmethod? please give me example

14th May 2019, 5:44 PM
kokito
7 Answers
+ 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
15th May 2019, 5:07 AM
Anna
Anna - avatar
+ 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__
14th May 2019, 6:17 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 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.
14th May 2019, 9:09 PM
Thoq!
Thoq! - avatar
+ 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)?
15th May 2019, 6:00 AM
Thoq!
Thoq! - avatar
+ 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.
15th May 2019, 6:46 AM
Anna
Anna - avatar
14th May 2019, 6:09 PM
Lothar
Lothar - avatar
+ 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?
14th May 2019, 6:44 PM
kokito