类列表视为全局

时间:2018-08-10 09:37:14

标签: python python-3.x

class City(Object):
    symbol = "1"
    name = "City"
    priority = 30 # Should actually be above mob layer.
    size = 5

    starting_citizens = 5
    citizens = []

    resources = {"food" : 100,
                 "wood" : 0,
                 "iron" : 0}

    inventory = []

    needs_processing = True
    action_time = 6

    def __init__(self, loc, x, y):
        global log
        log = log + "A new town has been settled!\n"
        self.name = self.name + " " + str(random.randrange(1, 999))
        super().__init__(loc, x, y)
        print(len(self.citizens))
        print("Procedure undergoing in: " + self.name)
        for N in range(self.starting_citizens - 1):
            print("Another one bites the city")
            self.add_citizen(Peasant)
        print("CITY INIT END")
        print(len(self.citizens))
        print(self.citizens)

    def add_citizen(self, citizen_type):
        print("Procedure undergoing in: " + self.name)
        print(str(len(self.citizens)) + " before adding occured")
        self.citizens.append(citizen_type(self, -2, -2)) #Huehuehue. -2 -2 won't be qdeled.
        print(str(len(self.citizens)) + " after adding occured")

出于各种原因,所有城市类对象都共享公民列表。每个方面都是相同的,我不想要什么。我希望每个班级都有自己的清单。

没有大量的调试帮助我看到了问题。

http://prntscr.com/kgz5as

1 个答案:

答案 0 :(得分:2)

这是因为您将citizens列表定义为类变量而不是实例变量。因此,它在所有实例之间共享。 (请参见Docs page on classes中的9.3.5)

实际上,您有多个变量可能应该是实例变量,而不是被类的所有实例共享(例如citizenssizename等)。像这样将它们定义为等距变量:

def __init__(self, loc, x, y):
    self.citizens = []