0

I have a class Map (simplified):

from Enums import *
import Globals
import Tile

class Map:
    tiles = []  #the actual map, it's a 2D list of Tile objects
    for x in range(Globals.mapWidth):
        for y in range(Globals.mapHeight):
            self.tiles[x][y].addItem(Items.Foliage)

And a class Tile:

class Tile:
    items=[]
    def __init__(self, type):
        self.type = type

    def addItem(self,i):
        self.items.append(i)

My problem is that the items[] array from the class Tile seems to be shared within every instanciation of the class. For example, at the end of the FOR loops, print(len(self.tiles[x][y].items) return 25 for every tile. Why is it so? I should have 25 lists of size 1, but instead printing the list size in the loop increases from 0 to 25. Can someone explan to me what happens here? Thanks a lot for the help :)

1 Answer 1

2

Your items is a class attribute, which is why it appears to be shared between all the instances.

class Tile:
    def __init__(self, type):
        self.items = []
        self.type = type
Sign up to request clarification or add additional context in comments.

4 Comments

That worked, thanks! I'll accept your answer when the website allows me
Say while you're here, how can I test if list.index() returns an error? I can't find this on Google.
@gramm: try: my_list.index(x); except ValueError: handle_error()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.