我试图初始化一个实例,但每次都会抛出一个错误:
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
我错过了什么
attributes
是在类中定义的,因此您需要通过类名引用它:类不定义新的范围;在
__init__
内部,在封闭范围中查找未在本地定义的非限定名称,该范围是class
语句出现的范围,而不是class
语句的主体您需要通过实例本身或实例的类型来查找该值
您将
attributes
定义为类成员。然后必须通过self.attributes
在类内部调用它。您还可以在__init__
内定义属性,并将生成的随机选择绑定到self.att
。但是只要['a', 'b', 'c']
是固定的(常数),这样做也可以相关问题 更多 >
编程相关推荐