Python中的几种定义类方法:常规方式,@property修饰方式,@classmethod修饰方式,@staticmethod修饰方式。
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传递当前类对象。
常规的类方法
定义时都需要通过self参数隐式的传递当前对象的实例。
调用时可以隐式或者显式
if __name__ == '__main__':
a = Test()
a.fun(1)
Test.fun(a, 1)
属性函数(@property):
- 将类方法转换为只读属性
- 重新实现一个属性的setter和getter方法
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)
运行结果:
10
类方法(@classmethod)
@classmethod修饰的方法需要通过cls参数传递当前类对象。
常规方法调用类的方法时必须实例化对象,但是类方法可以直接通过类来调用方法。
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)
@staticmethod修饰的方法定义与普通函数是一样的。只不过该方法位于类定义的命名空间中,不会对任何实例类型进行操作,类可以不用实例化也可以实例化后调用 。
特别强调的是,继承与覆盖普通类函数是一样的。
来源:oschina
链接:https://my.oschina.net/u/3647649/blog/2994756