python staticmethod,classmethod方法的使用和区别以及property装饰器的作用

时间:2023-03-09 12:58:43
python staticmethod,classmethod方法的使用和区别以及property装饰器的作用
class Kls(object):
def __init__(self, data):
self.data = data
def printd(self):
print(self.data)
@staticmethod
def smethod(*arg):
print('Static:', arg)
@classmethod
def cmethod(*arg):
print('Class:', arg) >>> ik = Kls(23)
>>> ik.printd()
23
>>> ik.smethod()
Static: ()
>>> ik.cmethod()
Class: (<class '__main__.Kls'>,)
>>> Kls.printd()
TypeError: unbound method printd() must be called with Kls instance as first argument (got nothing instead)
>>> Kls.smethod()
Static: ()
>>> Kls.cmethod()
Class: (<class '__main__.Kls'>,)
以上例子中printd是实例方法,smethod是静态方法,cmethod是类方法,那么他们有什么区别呢
实例方法会将实例自身作为第一个参数传给实例方法
lk.printd()会将lk传给printd方法
类方法
Kls.cmethod()会将Kls传给cmethod方法
当这个方法被调用的时候,我们把类作为第一个参数,而不是那个类的实例(就像我们通常用的方法一样)。这意味着您可以在该方法内使用该类及其属性,而不是特定的实例
静态方法不会传入类或者实例给类方法
当这个方法被调用的时候,我们不会把类的实例传递给它(就像我们通常用的方法一样)。这意味着你可以在一个类中放置一个函数,但是你不能访问那个类的实例(当你的方法不使用实例的时候这是很有用的)
通常的话使用实例方法即可,初始化类实例后,该实例可以调用类中的实例方法,
类方法是提供给类内部使用的,不需要初始化类实例。
静态方法在方法不使用实例是使用
例子链接:https://www.zhihu.com/question/20021164/answer/18224953
Python内置的@property装饰器就是负责把一个方法变成属性调用的