python - Différence entre staticmethod et classmethod

Mots clés : pythonoopmethodspython-decoratorspython

meilleur 4 Réponses python - Différence entre staticmethod et classmethod

vote vote

94

class A(object):     def foo(self, x):         print(f"executing foo({self}, {x})")      @classmethod     def class_foo(cls, x):         print(f"executing class_foo({cls}, {x})")      @staticmethod     def static_foo(x):         print(f"executing static_foo({x})")  a = A() 
a.foo(1) # executing foo(<__main__.A object at 0xb7dbef0c>, 1) 
a.class_foo(1) # executing class_foo(<class '__main__.A'>, 1) 
A.class_foo(1) # executing class_foo(<class '__main__.A'>, 1) 
a.static_foo(1) # executing static_foo(1)  A.static_foo('hi') # executing static_foo(hi) 
print(a.foo) # <bound method A.foo of <__main__.A object at 0xb7d52f0c>> 
print(a.class_foo) # <bound method type.class_foo of <class '__main__.A'>> 
print(a.static_foo) # <function static_foo at 0xb7d479cc> 
print(A.static_foo) # <function static_foo at 0xb7d479cc> 
vote vote

83

>>> class DictSubclass(dict): ...     def __repr__(self): ...         return "DictSubclass" ...  >>> dict.fromkeys("abc") {'a': None, 'c': None, 'b': None} >>> DictSubclass.fromkeys("abc") DictSubclass >>>  
vote vote

70

class C:     @classmethod     def f(cls, arg1, arg2, ...): ...  
class C:     @staticmethod     def f(arg1, arg2, ...): ...  
vote vote

60

class Apple:      _counter = 0      @staticmethod     def about_apple():         print('Apple is good for you.')          # note you can still access other member of the class         # but you have to use the class instance          # which is not very nice, because you have repeat yourself         #          # For example:         # @staticmethod         #    print('Number of apples have been juiced: %s' % Apple._counter)         #         # @classmethod         #    print('Number of apples have been juiced: %s' % cls._counter)         #         #    @classmethod is especially useful when you move your function to another class,         #       you don't have to rename the referenced class       @classmethod     def make_apple_juice(cls, number_of_apples):         print('Making juice:')         for i in range(number_of_apples):             cls._juice_this(i)      @classmethod     def _juice_this(cls, apple):         print('Juicing apple %d...' % apple)         cls._counter += 1 

Questions similaires