【发布时间】:2012-07-25 17:02:33
【问题描述】:
所以我正在尝试创建一个扩展列表的类,具有将某些特殊属性映射到引用列表的某些部分的额外能力。使用this Py3k doc page,我创建了以下代码。这个想法是(假设我有一个此类的sequence 实例)sequence.seq 的行为应该与sequence[0] 完全相同,sequence.index 的行为应该与sequence[2] 完全相同,等等。
它似乎工作得很好,除了我似乎无法访问到列表的类变量映射属性。
我找到了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 "<stdin>", line 1, in <module>
File "<stdin>", line 31, in __init__
File "<stdin>", line 17, in __setattr__
NameError: global name '__map__' is not defined
【问题讨论】:
标签: python python-3.x metaprogramming static-variables class-variables