python的类方法需要类作为第一个参数传入。通常用cls作为变量名字。而静态方法不需要self参数。并且它们在经典类和新式类中都可以调用。
class TestStaticMethod(object):
@staticmethod
def foo():
print ‘calling static method…’
class TestClassMethod(object):
@classmethod
def foo(cls):
print ‘the class’, cls.__name__, ‘is calling the class method foo()..’
In [7]: TestClassMethod.foo()
the class TestClassMethod is calling the class method foo()..
——————————–
In [8]: TestStaticMethod.foo()
calling static method…
——————————–
In [9]: a = TestStaticMethod()
In [10]: a.foo()
calling static method…
——————————–
In [10]: a.foo()
calling static method…
——————————–
In [11]: b = TestClassMethod()
In [12]: b.foo()
the class TestClassMethod is calling the class method foo()..
可见,在对象和实例中都可以调用。
In [15]: class C(TestStaticMethod):
….: pass
….:
In [16]: C.foo()
calling static method…
——————————-
In [17]: c = C()
In [18]: c.foo()
calling static method…
——————————-
In [19]: class D(TestClassMethod):
….: pass
….:
In [20]: D.foo()
the class D is calling the class method foo()..
——————————-
In [21]: d = D()
In [22]: d.foo()
the class D is calling the class method foo()..
在子类中仍然可就调用。类名会自动通过cls变量传入