2
3
4
5
6
'foo'
>>> c . foo
'foo'
>>> C . foo = 'bar'
>>> C . foo
'bar'
>>> c . foo
'bar'
>>> c . foo = 'instantiation'
>>> c . foo
'instantiation'
>>> C . foo
'bar'
calling static method foo().
>>> C . bar()
calling class method bar().
bar() is part of class: C
class C: def __init__(self): pass def foo(): print("calling static method foo().") foo = staticmethod(foo) def bar(a1,b): print("calling class method bar().") print("bar() is part of class:",a1.__name__) bar = classmethod(bar) C.foo() C.bar()----------------------------------------------------------------------------------------
TypeError: bar() takes exactly 2 arguments (1 given)
在PYTHON中,两种方法的主要区别在于参数。实例方法隐含的参数为类实例self,而类方法隐含的参数为类本身cls。
静态方法无隐含参数,主要为了类实例也可以直接调用静态方法。
所以逻辑上类方法应当只被类调用,实例方法实例调用,静态方法两者都能调用。主要区别在于参数传递上的区别,实例方法悄悄传递的是self引用作为参数,而类方法悄悄传递的是cls引用作为参数。
Python实现了一定的灵活性使得类方法和静态方法,都能够被实例和类二者调用
==========================================================================================================@staticmethod A way to write a method inside a class without reference to the object it is being called on. So no need to pass implicit argument like self or cls. It is written exactly the same how written outside the class, but it is not of no use in python because if you need to encapsulate a method inside a class since this method needs to be the part of that class @staticmethod is comes handy in that case.
@classmethod It is important when you want to write a factory method and by this custom attribute(s) can be attached in a class. This attribute(s) can be overridden in the inherited class.
A comparison between these two methods can be as below