class Books():
def __init__(self):
self.__dict__['referTable'] = 1
@property
def referTable(self):
return 2
book = Books()
print(book.referTable)
print(book.__dict__['referTable'])
Run Code Online (Sandbox Code Playgroud)
运行:
vic@ubuntu:~/Desktop$ python3 test.py
2
1
Run Code Online (Sandbox Code Playgroud)
Books.referTable 作为数据描述符不会被以下情况遮蔽book.__dict__['referTable']:
该
property()函数实现为数据描述符.因此,实例不能覆盖属性的行为.
要遮蔽它,而不是property内置描述符,我必须使用自己的描述符.是否有内置描述符,property但是非数据?
为了扩展我的评论,为什么不简单地这样:
>>> class Books():
... def __init__(self):
... self.__dict__['referTable'] = 1
... @property
... def referTable(self):
... try:
... return self.__dict__['referTable']
... except KeyError:
... return 2
...
>>> a = Books()
>>> a.referTable
1
>>> del a.__dict__['referTable']
>>> a.referTable
2
Run Code Online (Sandbox Code Playgroud)
现在,我想指出,我认为这不是一个好的设计,你最好不要使用私有变量而不是__dict__直接访问.例如:
class Books():
def __init__(self):
self._referTable = 1
@property
def referTable(self):
return self._referTable if self._referTable else 2
Run Code Online (Sandbox Code Playgroud)
简而言之,答案是否定的,没有其他选择可以property()在Python标准库中以您想要的方式工作.
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |