Python:将类属性在for循环中复制到该类的所有实例中

时间:2018-07-29 03:00:42

标签: python class for-loop

我有一班叫Station ...

class Station():
    def __init__(self):
        self.connecting_stations = []

...具有3个Station实例的列表...

stations = [Station() for n in range(3)]

...以及一个for循环,它将字符串"New Hampshire"附加到我的三个connecting_stations实例的Station属性中。

for station in stations:
    station.connecting_stations.append("New Hampshire")

当我print([station.connecting_stations for station in stations])打印时:

[
["New Hampshire", "New Hampshire", "New Hampshire"],
["New Hampshire", "New Hampshire", "New Hampshire"],
["New Hampshire", "New Hampshire", "New Hampshire"]
]

...即我的connecting_stations实例的全部Station属性的相同 "New Hampshire"重复了3次。

但是我真正想做的是:

>>> print(stations[0].connecting_stations)
["New Hampshire"]
>>> print(stations[1].connecting_stations)
["New Hampshire"]
>>> print(stations[2].connecting_stations)
["New Hampshire"]

...即我希望我的Station实例中的每个实例都有一个-只有一个-连接站,称为"New Hampshire",但实际上它们每个都获得3个"New Hampshire"字符串。

那怎么可能?发生了什么,我该如何解决我的问题?

实际完整代码:

import random
import turtle


class Game():

    def __init__(self, difficulty):
        number_of_stations = {
            "easy": 3,
            "medium": 5,
            "hard": 8
            }
        turtle.setworldcoordinates(0, -500, 500, 0)
        self.max_x = 500
        self.min_y = -500
        self.stations = self.create_stations(number_of_stations[difficulty])
        self.create_connections()

    def create_stations(self, number_of_stations):
        available_colors = [
            "#0A2463", "#3E92CC", "#C200FB", "#D8315B", "#1E1B18",
            "#564138", "#EEC643", "#F46036"
            ]
        available_xs = list(range(int(self.max_x*0.1), int(self.max_x*0.9)+1))
        available_ys = list(range(int(self.min_y*0.9), int(self.min_y*0.1)+1))
        stations = []
        # Adding stations (random color and random pos)
        for n in range(number_of_stations):
            station_color = available_colors.pop(random.randint(0, len(
                available_colors)-1))
            station_x = available_xs.pop(
                random.randint(0, len(available_xs)-1))
            station_y = available_ys.pop(
                random.randint(0, len(available_ys)-1))
            for x in range(station_x-int(self.max_x*0.05),
                           station_x+int(self.max_x*0.05)):
                if x in available_xs:
                    available_xs.remove(x)
            for y in range(station_y+int(self.min_y*0.05),
                           station_y-int(self.min_y*0.05)):
                if y in available_ys:
                    available_ys.remove(y)
            stations.append(Station(n, station_color, (station_x, station_y)))
        return stations

    def create_connections(self):
        for station in self.stations:
            station.connecting_stations.append("New Hampshire")


class Station():

    def __init__(self, identification,
                 color, position, connecting_stations=[]):
        self.id = identification
        self.color = color
        self.position = position
        self.x = self.position[0]
        self.y = self.position[1]
        self.connecting_stations = connecting_stations
        self.number_of_connections = len(self.connecting_stations)

        # Station's turtle instance setup
        self.turtle_instance = turtle.Turtle()
        self.turtle_instance.color(self.color)
        self.turtle_instance.speed("fastest")


game1 = Game("hard")

for station in game1.stations:
    print(station.id, station.connecting_stations)

注意:对不起,标题不好。没有找到更好更短的词来描述我的问题。

1 个答案:

答案 0 :(得分:0)

似乎您没有将类的3个不同实例添加到列表中,而是将同一个实例添加到列表中,然后对其进行3次修改,则将“ New Hapmshire”添加到了该实例3次。

尝试替换:

for station in stations:
    station.connecting_stations.append("New Hampshire")

使用

stations[0].connecting_stations.append("New Hampshire")

然后再次打印您的列表以查看=)