staticmethod和classmethod
@staticmethod 装饰的方法称为“静态方法”,@classmethod装饰的方法称为“类方法”或“类成员方法”。
在外部调用静态方法时,可以使用”类名.方法名”的方式,也可以使用”对象名.方法名”的方式。而实例方法只有后面这种方式。也就是说,调用静态方法可以无需创建对象。
静态方法在访问本类的成员时,只允许访问静态成员(即静态成员变量和静态方法),而不允许访问实例成员变量和实例方法;实例方法则无此限制。
类方法可以被对象调用,也可以被实例调用;传入的都是类对象,主要用于工厂方法,具体的实现就交给子类处理
静态方法参数没有实例参数 self, 也就不能调用实例参数
class a(object):
version = 1.0 #静态对象
#类方法可以被对象调用,也可以被实例调用;传入的都是类对象,
#主要用于工厂方法,具体的实现就交给子类处理
@classmethod
def test(cls):
return "a.test"
class b(a):
result = 'here!' #静态对象
def __init__(self, t='self here'):
self.t = t
def fun1(self): # 包含self关键字,即通过self来将方法绑定到对象
print "a.fun1", self
print self.t, self.result
@staticmethod
def fun2(a, b): #静态方法参数没有实例参数 self, 也就不能调用实例参数
print "a.fun2"
@classmethod
def fun3(cls):
print cls.test(), cls
print cls.result
self 和 cls
self 表示一个实例的本身,cls表示一个类的本身。类中普通的方法,第一个参数需要是self,它表示一个具体的实例本身。
如果用了staticmethod,那么就可以无视这个self,而将这个方法当成一个普通的函数使用。
而对于classmethod,它的第一个参数不是self,是cls,它表示这个类本身。
class a(object):
@classmethod
def test(cls):
return "a.test"
class b(a):
result = 'here!' #
def __init__(self, t='self here'):
self.t = t
def fun1(self):
print "a.fun1", self
print self.t, self.result
@staticmethod
def fun2():
print "a.fun2"
@classmethod
def fun3(cls):
print cls.test(), cls
print cls.result
if __name__ == '__main__':
test = b()
test.fun1()
test.fun2()
test.fun3()
print test.test()
运行结果:
a.fun1 <__main__.b object at 0x0000000002E661D0>
self here here!
a.fun2
a.test <class '__main__.b'>
here!
a.test
[Finished in 0.2s]