JohnHC
JohnHC

Reputation: 11205

NameError: name is not defined error in class __init__() method

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?

Upvotes: 5

Views: 1854

Answers (3)

chepner
chepner

Reputation: 531410

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

Upvotes: 4

colidyre
colidyre

Reputation: 4666

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.

Upvotes: 3

rdas
rdas

Reputation: 21285

attributes is defined inside the class, so you need to refer to it via the class name:

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

Upvotes: 2

Related Questions