0

I have a list of objects called TerrainTile. Each of these instances have a list called resourceList.

resourceList = []

I append an object called obj to this list within this method:

def add_resource_object (self, obj):
    self.resourceList.append(obj)
    return

For some reason, instead of each individual instance having its own list called resourceList, it seems all instances are sharing the same resourceList list and when it is appended to all instances are appended to.

Why is the .append() appending to all instances of TerrainTile?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
J Cline
  • 77
  • 7
  • 2
    The problem is that from the start your `self.resourceList` probably all point to the same list. You need to show how your class / instances are constructed, specially `self.resouourceList`. – Julien Apr 30 '18 at 01:25
  • 1
    Blind guess: you're defining `resourceList` in your class outside of your constructor. See https://stackoverflow.com/q/1680528/354577 (Side note: it would be more common to call this `resource_list` in Python code.) – ChrisGPT was on strike Apr 30 '18 at 01:30

2 Answers2

1

Based on your snippet above:

resourceList = []

You're creating a class variable shared between all instances, rather than an instance variable that's local to a particular instance. Instead, initialize your instance variable like so:

def __init__(self):
    self.resourceList = []

See here for details: https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables

jspcal
  • 50,847
  • 7
  • 72
  • 76
0

As stated in the comments and other answers, you are passing around the same instance variable to each list. Depending on the type of your object, you may be able to make a copy of it before adding it to each list.

Import it like this

from copy import deepcopy

Use it like this

new_obj = deepcopy(obj)
J. Darnell
  • 519
  • 7
  • 15