staticmethod classmethod修饰符

时间:2023-03-09 16:43:47
staticmethod classmethod修饰符

一、staticmethod(function)

Return a static method for function.
A static method does not receive an implicit first argument. To declare a static method, use this idiom:

class Sing():
@staticmethod
def sayHello():
print "hello world" def sayNo():
print "no" if __name__ == '__main__':
Sing.sayHello()
Sing.sayNo()

Sing.sayNo报错如下:

TypeError: unbound method sayNo() must be called with Sing instance as first argument (got nothing instead)
sayNo()方法非静态方法,需要先将对象Sing实例化才能调用该方法
而sayHello()方法不报错,因为staticmethod修饰
下面方法才是对的:

class Sing():
@staticmethod
def sayHello():
print "hello world" def sayNo(self):
print "no" if __name__ == '__main__':
Sing.sayHello()
sing = Sing()
sing.sayNo()

二、classmethod(function)

Return a class method for function.
A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class Sing():
@classmethod
def sayHello(self):
print "hello world" def sayNo(self):
print "no" if __name__ == '__main__':
Sing.sayHello()
sing = Sing()
sing.sayNo()

注意:staticmethod修饰的方法不需要接self参数,而classmethod修饰的方法则需要接self参数;

三、@property修饰符(新式类特有,新式类即接object定义的类)
修饰为类的属性,如下为不加@property修饰符的类的定义:

class C(object):
def __init__(self):
self._x = None def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")

通过@property修饰符修饰的类的定义:(从Python2.6开始引入setter,deleter,getter属性)

class C(object):
def __init__(self): self._x = None @property
def x(self):
"""I'm the 'x' property."""
return self._x @x.setter
def x(self, value):
self._x = value @x.deleter
def x(self):
del self._x