python类的静态变量,Python:从类内部访问静态类变量

所以我试图创建一个扩展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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值