所以我试图创建一个扩展list的类,它具有将某些特殊属性映射为引用列表的某些部分的额外功能。使用this Py3k doc page,我创建了以下代码。其思想是(假设我有一个sequence实例)sequence.seq应该与sequence[0]完全相同,sequence.index应该与{}完全相同,等等
它似乎工作得很好,只是我似乎无法访问类变量映射属性到列表。在
我找到了this 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 "", line 1, in
File "", line 31, in __init__
File "", line 17, in __setattr__
NameError: global name '__map__' is not defined