Definitions in Python:
- Class MyClass:
- ...
- Modifier for @classmethod # Classmethod
- Def class_method (CLS, arg1, Arg2, ...):
- ...
- Modifier for @staticmethod # Staticmethod
- def static_method (arg1, Arg2, ...):
- ...
@classmethod: Class Methods
@staticmethod: Static methods
A class method can be called directly from a class, just as a call to a static method.
The difference: Class method, need to pass in the class, define the class method to pass a default parameter CLS. Static methods are not used.
Example:
| 123456789101112131415161718192021222324252627282930313233343536373839 |
#!/usr/bin/env python# -*- coding: utf-8 -*-# blog.ithomer.netclass Test(object): x = 11 def __init__(self, _x): self._x = _x print("Test.__init__") @classmethod def class_method(cls): print("class_method") @staticmethod def static_method(): print("static_method") @classmethod def getPt(cls): cls.class_method() cls.static_method() if "__main__" == __name__: Test.class_method() # class_method Test.static_method() # static_method Test.getPt() # class_method static_method t = Test(22) # Test.__init__ t.class_method() # class_method t.static_method() # static_method print Test.x # 11# print Test._x print t.x # 11 print t._x # 22 # t.getPr() # ‘Test‘ object has no attribute ‘getPr‘ |
Operation Result:
| 1234567891011121314 |
class_methodstatic_methodclass_methodstatic_methodTest.__init__class_methodstatic_method111122Traceback (most recent call last): File "/home/homer/workspace/myPython/com/connmiliao.py", line 40, in <module> t.getPr() AttributeError: ‘Test‘ object has no attribute ‘getPr‘</module> |
Example: @property, @staticmethod, @classmethod
| 12345678910111213141516171819202122232425262728293031323334353637383940 |
#!/usr/bin/env python# -*- coding: utf-8 -*-# blog.ithomer.netclass MyClass(object): def __init__(self): print ‘__init__‘ self._name = ‘blog.ithomer.net‘ @staticmethod def static_method(): print ‘This is a static method!‘ def test(self): print ‘call test‘ @classmethod def class_method(cls): print ‘cls: ‘,cls print ‘cls.name: ‘,cls.name print ‘cls.static_method(): ‘,cls.static_method() instance = cls() print ‘instance.test(): ‘,instance.test() @property def name(self): return self._name @name.setter def name(self, value): self._name = valueif __name__ == ‘__main__‘: MyClass.static_method() MyClass.class_method() mc = MyClass() print mc.name mc.name = ‘forum.ithomer.net‘ print mc.name |
Operation Result:
This is a static method!
CLS: <class ' __main__.myclass ' = "" >
Cls.name:
Cls.static_method (): This is a static method!
None
__init__
Instance.test (): Call test
None
__init__
Blog.ithomer.net
Forum.ithomer.net
Python--@classmethod @staticmethod differences and use