我正在构建一个继承自Foo
的python3对象list
。实际上,它是语言分析的语法标记。我需要以下行为:
Foo
必须是可迭代的Foo.__init__()
Foo.method()
Foo.foo0 is Foo[0]
(不仅是Foo.attr [0] == Foo [0])其他一些属性不需要在"列表"。
中我找到了一种方法,但我怀疑必须有一种更干净,更灵巧的方式。此外,欢迎任何性能和内存使用方面的改进。这是我的代码:
class Foo(list):
def __init__(self, foo1, foo2):
# there is 13 attributes
# setters raise IndexError without this hack :
[self.append(x) for x in [None]*13]
# first pack of attribute
self.foo1 = foo1
self.foo2 = foo2
# ... etc
# getter and setter for init attributes
@property
def foo1(self): return self[0]
@foo1.setter
def foo1(self,value): self[0] = value
# same thing for foo2, foo3... etc
## getter and setter for other attributes
@property
def bar1(self): return self[10]
@bar1.setter
def bar1(self,value): self[10] = value
# same thing for bar2, bar3... etc
def method(self, value1, value2):
self.bar1 = value1
self.bar2 = value2
# ... etc
# init object
f= Foo('some string', 'some other string')
# later :
f.method('data', 'more data')
# expected behavior
assert f.foo1 is f[0]
assert f.bar1 is f[10]
我不确定我做得对..特别是这个黑客攻击:
[self.append(x) for x in [None]*13]
你能想到一个更好的方法吗?
编辑: 经过一些基准测试后,由于MartijnPieters评论,我确实保存了性能:
self.extend(None for _ in range(13))