首页 > 解决方案 > 实例作为另一个实例的位置参数

问题描述

如果我有这个代码:

class Location():
    def __init__(self, north, south, east, west):
        self.north = north
        self.south = south
        self.east = east
        self.west = west

ruins = Location(forest1,beach1,forest2,beach2)
forest1 = Location(forest3,ruins,forest4,beach3)

有没有办法将实例用作上述位置参数的值,或者有更好的方法吗?我不断得到,forest1 not defined因为它在分配之前被引用,但要这样做,有些人必须这样做。我相信我已经回答了自己,这是不可能的,所以我怎样才能获得这种设置。

标签: pythonpython-3.x

解决方案


不,您不能在声明之前使用变量。您可以做的是允许初始化空对象,并稍后填充属性:

class Location():
    def __init__(self):
        pass

    def set_directions(self, north, south, east, west):
        self.north = north
        self.south = south
        self.east = east
        self.west = west

ruins = Location()
forest1 = Location()
# ...
ruins.set_directions(forest1, beach1, forest2, beach2)
forest1.set_directions(forest3, ruins, forest4, beach3)

推荐阅读