Python中的几种定义类方法:常规方式,@property修饰方式,@classmethod修饰方式,@staticmethod修饰方式。python
class Test(object): def __init__(self): self.name = 'eappo' def fun(self, x): print('self:', self, x) @property def property_fun(self): print('@property', self, self.name) @classmethod def class_fun(cls, x): print('@classmethod cls:', cls, x) @staticmethod def static_fun(x): print('@staticmethod', x) if __name__ == '__main__': a = Test() a.fun('fun') a.property_fun a.class_fun('class_fun') a.static_fun('static_fun')
运行结果: 编程
self: <__main__.Test object at 0x0000023DC8BAD208> fun @property <__main__.Test object at 0x0000023DC8BAD208> eappo @classmethod cls: <class '__main__.Test'> class_fun @staticmethod static_fun
self和cls的区别不是强制的,只是PEP8中一种编程风格,self一般用做实例方法的第一参数,cls一般用做类方法的第一参数。即一般用self来传递当前类对象的实例,cls传递当前类对象。app
定义时都须要经过self参数隐式的传递当前对象的实例。函数
调用时能够隐式或者显式ui
if __name__ == '__main__': a = Test() a.fun(1) Test.fun(a, 1)
class TestProperty(object): @property def score(self): return self._score @score.setter def score(self, v): self._score = v if __name__ == '__main__': s = TestProperty() s.score = 10 print(s.score)
运行结果:spa
10
@classmethod修饰的方法须要经过cls参数传递当前类对象。code
常规方法调用类的方法时必须实例化对象,可是类方法能够直接经过类来调用方法。对象
if __name__ == '__main__': Test.class_fun(1) Test.fun(1)
运行结果:继承
@classmethod cls: <class '__main__.Test'> 1 Traceback (most recent call last): File "F:/PythonSpace/ClassMethod/Test.py", line 31, in <module> Test.fun(1) TypeError: fun() missing 1 required positional argument: 'x'
@staticmethod修饰的方法定义与普通函数是同样的。只不过该方法位于类定义的命名空间中,不会对任何实例类型进行操做,类能够不用实例化也能够实例化后调用 。get