class Books():
def __init__(self):
self.__dict__['referTable'] = 1
@property
def referTable(self):
return 2
book = Books()
print(book.referTable)
print(book.__dict__['referTable'])
运行中:
^{pr2}$Books.referTable
being a data descriptor没有被book.__dict__['referTable']
遮蔽:
The
property()
function is implemented as a data descriptor. Accordingly, instances cannot override the behavior of a property.
为了隐藏它,我必须使用我自己的描述符,而不是property
内置描述符。是否有一个内置描述符,如property
,但哪一个不是数据?在
为了扩展我的评论,为什么不简单地这样做:
现在,我想指出的是,我认为这不是一个好的设计,使用私有变量比直接访问
^{pr2}$__dict__
要好得多。E、 g组:简而言之,答案是否定的,除了
property()
之外,没有其他方法可以在Python标准库中以您想要的方式工作。在与内置的非数据描述符class属性非常相似:
如果您需要更像属性的东西(例如,您希望一个函数在第一次执行一些繁重的工作,但随后将第一个值用于所有将来的引用),则需要您自己构建它:
^{pr2}$结果如下:
相关问题 更多 >
编程相关推荐