zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python装饰器@property

Python 装饰 Property
2023-09-27 14:29:16 时间

@property可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式,但是有时候setter/deleter也是需要的。
1、只有@property表示只读。
2、同时有@property和@*.setter表示可读可写。

3、同时有@property和@*.setter和@*.deleter表示可读可写可删除。

 

class A(object):  # 要求继承object
def __init__(self):
self.__name = None

# 下面开始定义属性,3个函数的名字要一样!
@property # 读
def name(self):
return self.__name

@name.setter # 写
def name(self, value):
self.__name = value

@name.deleter # 删除
def name(self):
del self.__name


a = A()
print(a.name ) # 读
a.name = 'python' # 写
print(a.name ) # 读
del a.name # 删除
print(a.name) # a.name已经被删除 AttributeError: 'A' object has no attribute '_A__name'

运行结果:

F:\dev\python\python.exe F:/pyCharm/practice/config_dir/property_demo2.py
None
Traceback (most recent call last):
python
File "F:/pyCharm/practice/config_dir/property_demo2.py", line 24, in <module>
print(a.name) # a.name已经被删除 AttributeError: 'A' object has no attribute '_A__name'
File "F:/pyCharm/practice/config_dir/property_demo2.py", line 8, in name
return self.__name
AttributeError: 'A' object has no attribute '_A__name'

Process finished with exit code 1