python-静态方法与类方法的区别

很多人都知道通过@staticmethod和@classmethod来分别定义静态方法和类方法,一个带参数cls,一个不带参数,而且同样都能被类实例或者类调用,那他们具体有什么区别呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Parent(object):
@staticmethod
def name(name):
print 'parent'
@staticmethod
def static_method():
Parent.name()
@classmethod
def class_method(cls):
cls.name()
#Parent.name() #这里使用cls会调用son的name方法,使用Parent会调用parent的name方法
class Son(Parent):
@staticmethod
def name():
print 'son'
s = Son()
s.static_method()
s.class_method()