Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 762
JohnHC Avatar asked Dec 31 '22 07:12

JohnHC


2 Answers

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
like image 177
chepner Avatar answered Jan 02 '23 20:01

chepner


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.

like image 31
colidyre Avatar answered Jan 02 '23 21:01

colidyre