您可以构建一个自定义类,__slots__
用于限制使用的内存量:
class MutableEfficientNamedList(object):
__slots__ = ('field1', 'field2', 'field3')
def __init__(self, *values):
for k, v in zip(self.__slots__, values):
setattr(self, k, v)
def __getitem__(self, i):
return getattr(self, self.__slots__[i])
def __setitem__(self, i, v):
return setattr(self, self.__slots__[i], v)
def __repr__(self):
return '{}({})'.format(type(self).__name__,
', '.join(repr(getattr(self, s)) for s in self.__slots__))
然后在你的结构中使用它们。它们可以像命名元组一样使用(允许按索引和名称访问),但它们允许变异。通过使用__slots__
每个实例的内存占用量仍然很低:
>>> menl = MutableEfficientNamedList('foo', 'bar', 'baz')
>>> menl
MutableEfficientNamedList('foo', 'bar', 'baz')
>>> menl.field1
'foo'
>>> menl[0]
'foo'
>>> menl[1]
'bar'
>>> menl[1] = 'spam'
>>> menl.field2
'spam'
您当然要为插槽提供有意义的名称,并且请为您的班级选择一个比我在示例中使用的名称更好的名称。:-)
为了扩展该namedtuple()
模式,这里是一个通用工厂函数:
def namedlist(name, *attrs):
"""Create a named list class named `name` with attributes `attrs`.
`attrs` must be strings representing valid Python identifiers.
"""
class MutableEfficientNamedList(object):
__slots__ = attrs
def __init__(self, *values):
for k, v in zip(self.__slots__, values):
setattr(self, k, v)
def __getitem__(self, i):
return getattr(self, self.__slots__[i])
def __setitem__(self, i, v):
return setattr(self, self.__slots__[i], v)
def __repr__(self):
return '{}({})'.format(type(self).__name__,
', '.join(repr(getattr(self, s)) for s in self.__slots__))
MutableEfficientNamedList.__name__ = name
return MutableEfficientNamedList
MyList = namedlist('MyList', 'foo', 'bar', 'baz')
nl = MyList(1, 2, 3)
print nl # MyList(1, 2, 3)
print nl.bar # 2
print nl[1] # 2