0

So I have the following code:

class Table:
    children = [False, False]

    def __repr__(self):
        return str(self.children)


classroom = [Table(), Table(), Table(), Table()]


def update():
    classroom[1].children[0] = True
    print(classroom)


update()

Which is supposed to edit the second element within the list "classroom" and print out:

[[False, False], [True, False], [False, False], [False, False]]

But somehow updating the list on line 12 updates every instance of the class, giving me this:

[[True, False], [True, False], [True, False], [True, False]]

I've tried using the global keyword within the function but it seems to have no affect, am I missing something?

Isiah
  • 195
  • 2
  • 15
  • 3
    `children` is a class variable, meaning its shared between all instances of `Table`. You need to make it an instance variable if you want them to have different values. – rchome Dec 18 '21 at 18:13
  • Also check https://stackoverflow.com/q/207000/4046632 – buran Dec 18 '21 at 18:22

1 Answers1

3

children is a class variable, associated with the class rather than the instance. When you change it on one occasion, it gets updated in every existing instance of that class - the four instances of Table in your case.

To achieve the desired behavior you need to make children an instance variable. One common way to do it is to introduce an __init__ method that is called when you create an instance,

class Table:

    def __init__(self):
        self.children = [False, False]

    def __repr__(self):
        return str(self.children)

Now every instance of Table, when created, calls its own __init__ and makes its own children list. Later, when you update the second Table the changes are correctly reflected only in that one case.

atru
  • 4,699
  • 2
  • 18
  • 19
  • Gladly! Consider doing some more reading on class structure in Python, there are a few good things that are very helpful. – atru Dec 18 '21 at 21:40