>>> class MyClass():
... def thisIsClassMethod(self):
... print ("this is a class method")
...
>>> MyClass().thisIsClassMethod()
this is a class method
>>> MyClass.thisIsClassMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: thisIsClassMethod() missing 1 required positional argument: 'self'
class MyClass:
@staticmethod
def thisIsStaticMethod():
print("This is static method")
if __name__ == "__main__":
MyClass.thisIsStaticMethod()
property修饰符
被property修饰符修饰的方法可以像属性一样被访问,如
class MyClass:
def __init__(self,num):
self._Num = num
@property
def Num(self):
return self._Num
if __name__ == "__main__":
c = MyClass(100)
print c.Num #注意,这里的访问形式看起来像是访问一个属性,但其实是一个方法
修饰器property类的使用:
#!/use/bin/python3
class Person(object):
def __init__(self):
self.__x = None
@property
def x(self):
return self.__x
@x.setter
def x(self, value):
self.__x = value
@x.deleter
def x(self):
del self.__x
p = Person()
p.x = 123 # 自动调用 setx 方法
print(p.x) # 自动调用 getx 方法
del p.x # 自动调用 delx 方法
print(p.x)
通过property类可以使得类的方法可以像属性一样使用,使代码更为简洁
|deleter(...) | Descriptor to change the deleter on a property. |
| getter(...) | Descriptor to change the getter on a property. |
| setter(...) | Descriptor to change the setter on a property.