我想创建一个有多个类级变量的类,其中一些具有引用先前声明的类级变量的计算值。但是,我在某些时候很难引用这些变量。python类变量分配不规则
我第一次尝试:
#!/usr/bin/env python
from decimal import Decimal
import math
class Foo(object):
NUM_BUCKETS = 10
BUCKET_SIZE = Decimal(1.0/NUM_BUCKETS)
BUCKET_LABELS = tuple("BUCKET_{}".format(int(BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
print Foo.BUCKET_LABELS
结果:
> python test.py
Traceback (most recent call last):
File "test.py", line 5, in <module>
class Foo(object):
File "test.py", line 8, in Foo
BUCKET_LABELS = tuple("BUCKET_{}".format(int(BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
File "test.py", line 8, in <genexpr>
BUCKET_LABELS = tuple("BUCKET_{}".format(int(BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
NameError: global name 'BUCKET_SIZE' is not defined
尝试通过类名来访问类变量无法正常工作或:
#!/usr/bin/env python
from decimal import Decimal
import math
class Foo(object):
NUM_BUCKETS = 10
BUCKET_SIZE = Decimal(1.0/NUM_BUCKETS)
BUCKET_LABELS = tuple("BUCKET_{}".format(int(Foo.BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
print Foo.BUCKET_LABELS
结果:
> python test2.py
Traceback (most recent call last):
File "test2.py", line 5, in <module>
class Foo(object):
File "test2.py", line 8, in Foo
BUCKET_LABELS = tuple("BUCKET_{}".format(int(Foo.BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
File "test2.py", line 8, in <genexpr>
BUCKET_LABELS = tuple("BUCKET_{}".format(int(Foo.BUCKET_SIZE * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
NameError: global name 'Foo' is not defined
用硬编码值替换对BUCKET_SIZE的引用可修复问题;即使是在同一线路的其它类级变量引用,它工作得很好:
#!/usr/bin/env python
from decimal import Decimal
import math
class Foo(object):
NUM_BUCKETS = 10
BUCKET_SIZE = Decimal(1.0/NUM_BUCKETS)
BUCKET_LABELS = tuple("BUCKET_{}".format(int(Decimal(0.1) * i * 100)) for i in xrange(1, NUM_BUCKETS + 1))
print Foo.BUCKET_LABELS
结果:
> python test3.py
('BUCKET_10', 'BUCKET_20', 'BUCKET_30', 'BUCKET_40', 'BUCKET_50', 'BUCKET_60', 'BUCKET_70', 'BUCKET_80', 'BUCKET_90', 'BUCKET_100')
有谁知道在那个地方引用BUCKET_SIZE的正确方法是什么?这是Python本身的错误吗? (我运行的Python 2.7.5,顺便说一句。)
这看起来像是生成器表达式范围的问题,因为当我将其更改为列表理解时,错误消失。 – TigerhawkT3
另外NUM_BUCKETS在发生器中工作良好,只是在与BUCKET_SIZE部分问题 –
本质上是一个愚蠢的[这个问题](http://stackoverflow.com/questions/20136955/python3-nested-list-comprehension-scope),除该问题在Python 3上,并使用列表理解。我没有看到任何使用Genexps的优秀候选人。 – user2357112