I'm trying to initialise an instance, but I'm throwing an error every time:
import random
class cGen:
attributes = ['a','b','c']
def __init__(self):
self.att = random.choice(attributes)
I can import the class just fine, but get an error:
>>> 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
What am I missing here?
A class does not define a new scope; inside __init__
, an unqualified name that isn't defined locally is looked up in the enclosing scope, which is the scope in which the class
statement occurs, not the body of the class
statement.
You'll need to look up the value via either the instance itself, or via the type of the instance.
def __init__(self):
self.att = random.choice(self.attributes) # or type(self).attributes
You defined attributes
as a class member. Then you have to call it inside the class via self.attributes
. You can also define attributes inside __init__
and bind the resulting random choices to self.att
. But as long as ['a', 'b', 'c']
is fixed (constant), it is also ok doing it this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With