property 属性
类函数通过property属性的处理,调用该函数方法时可以直接调用,相当于调用类属性一样不用加括号。
property属性有2中方式
1、装饰器方式(经典类和新式类)
经典类,只有@property装饰器:
class Paper:
# 类属性
length = 1.8
def __init__(self, color):
# 实例属性
self.color = color
@property
def common_func(self):
return self.color
if __name__ == '__main__':
p = Paper("yello")
result = p.common_func
print(result)
输出:
"C:\Program Files\Python39\python.exe" E:/caicai/test.py
yello
Process finished with exit code 0
新式类,有三种@property装饰器
class Paper(object):
def __init__(self):
# 实例属性
self.per_length = 2
self.num = 3
@property
def length(self):
new_length = self.per_length * self.num
return new_length
@length.setter
def length(self, value):
self.per_length = value
@length.deleter
def length(self):
del self.per_length
if __name__ == '__main__':
p = Paper()
p.length # 获取长度属性
print(p.length)
p.length = 3 # 修改长度属性
print(p.length)
del p.length # 删除长度属性
print(p.length) # 删除后输出报错,该属性不存在
输出如下:
"C:\Program Files\Python39\python.exe" E:/caicai/property_test.py
Traceback (most recent call last):
6
File "E:\caicai\property_test.py", line 30, in <module>
9
print(p.length)
File "E:\caicai\property_test.py", line 10, in length
new_length = self.per_length * self.num
AttributeError: 'Paper' object has no attribute 'per_length'
Process finished with exit code 1
2、类属性方式
class Paper(object):
def __init__(self):
# 实例属性
self.per_length = 2
self.num = 3
def get_length(self):
new_length = self.per_length * self.num
return new_length
def set_length(self, value):
self.per_length = value
def del_length(self):
del self.per_length
LENGTH = property(get_length, set_length, del_length, "属性描述....")
if __name__ == '__main__':
p = Paper()
p.LENGTH # 获取长度属性
print(p.LENGTH)
p.LENGTH = 3 # 修改长度属性
print(p.LENGTH)
del p.LENGTH # 删除长度属性
print(p.LENGTH)
输出如下:
"C:\Program Files\Python39\python.exe" E:/caicai/property_test.py
Traceback (most recent call last):
6
File "E:\caicai\property_test.py", line 30, in <module>
9
print(p.length)
File "E:\caicai\property_test.py", line 10, in length
new_length = self.per_length * self.num
AttributeError: 'Paper' object has no attribute 'per_length'
Process finished with exit code 1