所以我正在尝试创建一个扩展列表的类,具有将某些特殊属性映射到引用列表的某些部分的额外能力。使用这个 Py3k 文档页面,我创建了以下代码。这个想法是(假设我有sequence
这个类的一个实例)sequence.seq
应该完全像sequence[0]
,并且sequence.index
应该完全像sequence[2]
,等等。
它似乎工作得很好,除了我似乎无法访问列表的类变量映射属性。
我发现了这个 SO question,但是答案有误,或者方法中的某些内容有所不同。我也可以使用self.__class__.__map__
,但因为我需要里面的类变量__getattribute__
,所以我进入了一个无限递归循环。
>>> class Sequence(list):
... __map__ = {'seq': 0,
... 'size': 1,
... 'index': 2,
... 'fdbid': 3,
... 'guide': 4,
... 'factors': 5,
... 'clas': 6,
... 'sorttime': 7,
... 'time': 8,
... 'res': 9,
... 'driver': 10 }
...
... def __setattr__(self, name, value): # "Black magic" meta programming to make certain attributes access the list
... print('Setting atr', name, 'with val', value)
... try:
... self[__map__[name]] = value
... except KeyError:
... object.__setattr__(self, name, value)
...
... def __getattribute__(self, name):
... print('Getting atr', name)
... try:
... return self[__map__[name]]
... except KeyError:
... return object.__getattribute__(self, name)
...
... def __init__(self, seq=0, size=0, index=0, fdbid=0, guide=None, factors=None,
... sorttime=None, time=None):
... super().__init__([None for i in range(11)]) # Be sure the list has the necessary length
... self.seq = seq
... self.index = index
... self.size = size
... self.fdbid = fdbid
... self.guide = ''
... self.time = time
... self.sorttime = sorttime
... self.factors = factors
... self.res = ''
... self.driver = ''
...
>>> a = Sequence()
Setting atr seq with val 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 31, in __init__
File "<stdin>", line 17, in __setattr__
NameError: global name '__map__' is not defined