NameError:未定义名称类_uinit__;方法中的错误

2024-06-24 13:45:24 发布

您现在位置: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

我错过了什么


Tags: 实例inimportselfinitdef错误line
3条回答

attributes是在类中定义的,因此您需要通过类名引用它:

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

类不定义新的范围;在__init__内部,在封闭范围中查找未在本地定义的非限定名称,该范围是class语句出现的范围,而不是class语句的主体

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

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

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

相关问题 更多 >