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
相关文章
- Python 没有函数重载?如何用装饰器实现函数重载?
- python的特殊数字类型(无穷大、无穷小等)
- Python面试题之装饰器漫谈
- Python power spectral 功率谱
- [Python]PyCharm中出现unresolved reference的解决方法
- 【Python】 Django 怎么实现 联合主键?
- Python 字符串前面加u,r,b,f的含义
- 一文看懂Python系列之装饰器(decorator)
- Python 装饰器
- python的@是什么(函数装饰器)
- 流畅的python第十八章使用asyncio包处理并发
- (转)python装饰器进阶一
- 【网络编程5】Java与Python套接字Socket通信的例子
- Installing mysqlclient in Python 3.6 in windows
- 第8.27节 Python中__getattribute__与property的fget、@property装饰器getter关系深入解析
- python闭包以及装饰器
- python chromedriver.exe下载
- 关于python装饰器(Decorators)最底层理解的一句话
- Python 进阶_闭包 & 装饰器
- Python - 闭包和装饰器