Dan149
Dan149

Reputation: 46

How to append content to a list in a class without impacting other instances of it?

I try to append content to a list in a class, the problem is when I do it for one of my instances, it has the same effect on the others. This is a simplified version of my code:

class Dir:
    content = []
    name = None

home = Dir()
home.name = "home"
home.content.append("Desktop")

sys = Dir()
sys.name = "home"

print(str(home.content))
print(str(sys.content))

When I execute the script, the result is:

['Desktop']
['Desktop']

Upvotes: 0

Views: 154

Answers (2)

quamrana
quamrana

Reputation: 39404

When you have a class like this:

class Dir:
    content = []
    name = None

both content and name start off as class attributes, which are available immediately as Dir.content and Dir.name.

Each time you create an instance of the class: home = Dir(), the instance gets copies of the same references, so home.content == Dir.content and home.name == Dir.name.

However, when you execute: home.name = "home", then you overwrite the instance variable's name attribute with a reference to "home".

Now Dir.name == None still, but home.name == "home".

Now the next part: home.content.append("Desktop") you only reference the content attribute to call the append() method. Now, both the class and instance content attribute contain ['Desktop'].

Make sure you read this excellent article by Ned Batchelder

Upvotes: 0

ant1g
ant1g

Reputation: 1009

You should declare your instance variables in the constructor:

class Dir:
  def __init__(self):
    self.content = []
    self.name = None

Upvotes: 1

Related Questions