【发布时间】:2018-05-14 14:27:15
【问题描述】:
如何创建一个始终包含相同列表的类属性?尽管列表的内容可以更改,但它应该始终引用同一个列表。
显而易见的解决方案是使用属性。
class Table(list):
def filter(kwargs):
"""Filter code goes here."""
class db:
_table = Table([1, 2])
table = property(lambda self: self._table)
db.table.append(3)
我会假设 db.table 应该返回一个列表,并且您应该能够附加到这个列表。但是不行,这段代码会抛出异常:
AttributeError: 'property' object has no attribute 'append'
如何创建始终引用同一个列表的属性?
插图:
db.table = [x for x in db.table if x > 2]
db.filter(3) # This filter method got lost when reassigning the table in the previous line.
【问题讨论】:
-
class db: table = [1, 2]有什么问题? -
db是一个类,你想要一个实例。 -
例如你应该做
db().table.append(3)来创建一个实例...... -
我看不出类属性的类型有多重要。除非您重新分配它,否则它将始终是同一个实例。
-
您可以在元类中定义属性,如 here 所示,或者 - 这可能是更好的解决方案 - 使
db成为实例而不是类。
标签: python