1
class Example:
    my_list = [1, 2, 3]
    def __init__(self):
        self.my_list = my_list


example = Example()

print(example.my_list)

running the above code returns this NameError: name 'my_list' is not defined.

class Example:
    my_list = [1, 2, 3]
    def __init__(self):
        global my_list
        self.my_list = my_list


example = Example()

Using global doesn't seem to work either. What could be going on? why can't you instantiate an attribute using global?

Ser.T
  • 51
  • 4
  • 1
    Does this answer your question? [python class variable accessible from class method?](https://stackoverflow.com/questions/28119489/python-class-variable-accessible-from-class-method) – Alex Waygood Sep 05 '21 at 19:05

1 Answers1

0

You don't need to set self.my_list = my_list, because my_list is already an attribute of Example:

class Example:
    my_list = [1, 2, 3]
    def __init__(self):
        pass


example = Example()

print(example.my_list)

You could alternatively define my_list in the __init__ method:

class Example:
    def __init__(self):
        self.my_list = [1, 2, 3]


example = Example()

print(example.my_list)
Sylvester Kruin
  • 3,294
  • 5
  • 16
  • 39