NameError:类__init __()方法中的名称未定义错误

时间:2020-02-09 21:55:26

标签: python

我正在尝试初始化一个实例,但是每次都抛出一个错误:

import random
class cGen:
    attributes = ['a','b','c']
    def __init__(self):
        self.att = random.choice(attributes)

我可以很好地导入该类,但是会出现错误:

>>> c1 = cGen()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".\xGen.py", line 288, in __init__
    self.att = random.choice(attributes)
NameError: name 'attributes' is not defined

我在这里想念什么?

3 个答案:

答案 0 :(得分:4)

一个类没有定义新的作用域;在__init__内部,在封闭范围内查找未本地定义的不合格名称,该范围是class语句所在的范围,而不是class语句的主体

您需要通过实例本身或实例的类型来查找值。

def __init__(self):
    self.att = random.choice(self.attributes)  # or type(self).attributes

答案 1 :(得分:2)

attributes是在类内部 中定义的,因此您需要通过类名称进行引用:

import random
class cGen:
    attributes = ['a','b','c']
    def __init__(self):
        self.att = random.choice(cGen.attributes)

答案 2 :(得分:2)

您将attributes定义为班级成员。然后,您必须通过self.attributes在班级内部调用它。您还可以在__init__内定义属性,并将结果的随机选择绑定到self.att。但是只要['a', 'b', 'c']是固定的(恒定),就可以这样做。

相关问题