【问题标题】:How to force a instance attribute to always be a list?如何强制实例属性始终是列表?
【发布时间】:2019-10-09 05:11:35
【问题描述】:
我有一个包含许多属性的类。我希望有一个属性始终是list,即它不能被其他任何东西覆盖,它的行为总是像list。
class SomeClass(object):
def __init__(self):
self.var1 = None
self.var2 = None
self.alwaysList = []
sc = SomeClass()
sc.alwaysList.append("Something") # Valid
sc.alwaysList = 5 # Should be invalid
我应该编写包装函数吗?我应该使用@property吗?
【问题讨论】:
标签:
python
list
properties
wrapper
【解决方案1】:
您可以使用@property 和@alwaysList.setter 来定义设置道具时的行为。您可以在 setter 中严格执行列表类型(或测试抽象基类:isinstance(newVal, collections.Sequence)),或者(可能更 Pythonic)采用可迭代的任何内容并转换为列表:
class SomeClass(object):
def __init__(self):
self.var1 = None
self.var2 = None
self._alwaysList = []
@property
def alwaysList(self):
return self._alwaysList
@alwaysList.setter
def alwaysList(self, newVal):
''' a little more forgiving of input '''
try:
self._alwaysList = list(newVal)
except TypeError:
# print warning or raise
print("alwaysList must be iterable: {} is not iterable".format(newVal))
sc = SomeClass()
sc.alwaysList.append("Something") # Valid
sc.alwaysList = 90 # error alwaysList must be iterable: 90 is not iterable
sc.alwaysList = "somthing" # string is iterable -- convert to list
sc.alwaysList # ['s', 'o', 'm', 't', 'h', 'i', 'n', 'g']
使用上面的方法更灵活——你可以传入任何可迭代的东西,比如sc.alwaysList = range(10),同时仍然总是在属性中有一个列表。