属性的内置非数据版本?

2024-09-30 20:28:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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.referTablebeing 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,但哪一个不是数据?在


Tags: selfdatareturninitdefpropertybooks内置
2条回答

为了扩展我的评论,为什么不简单地这样做:

>>> 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

现在,我想指出的是,我认为这不是一个好的设计,使用私有变量比直接访问__dict__要好得多。E、 g组:

^{pr2}$

简而言之,答案是否定的,除了property()之外,没有其他方法可以在Python标准库中以您想要的方式工作。在

与内置的非数据描述符class属性非常相似:

class Books():

    referTable = 'default'

    def __init__(self, referTable=None):
        if referTable is not None:
            self.referTable = referTable


book = Books()
print(book.referTable)
# default
book.referTable = 'something specific'
print(book.referTable)
# something specific

如果您需要更像属性的东西(例如,您希望一个函数在第一次执行一些繁重的工作,但随后将第一个值用于所有将来的引用),则需要您自己构建它:

^{pr2}$

结果如下:

{}
calculating
120
{'referTable': 120}
120

相关问题 更多 >