今日在检查代码的时候,发现其中有四个名词:staticmethod、classmethod、self和cls。怕日后记不清楚了,因此特意记录下来,以便日后翻阅查看,并且可以帮助其他的 Pythoner 们。
- staticmethod和classmethod
staticmethod 可以称为“静态方法”,classmethod可以称为“类成员方法”。
两者的相同点是:都可以通过实例或者类来访问;都不能访问实例的成员变量。
两者之间不同点有:staticmethod无需参数,classmethod需要类变量作为参数传递(不是类的实例);classmethod可以访问类成员,staticmethod则不可以
示例:
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
- 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 0x0247B810>
self here here!
a.fun2
a.test <class '__main__.b'>
here!
a.test