python - 实例作为另一个实例的位置参数
问题描述
如果我有这个代码:
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
因为它在分配之前被引用,但要这样做,有些人必须这样做。我相信我已经回答了自己,这是不可能的,所以我怎样才能获得这种设置。
解决方案
不,您不能在声明之前使用变量。您可以做的是允许初始化空对象,并稍后填充属性:
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)
推荐阅读
- logstash - 如何根据单列条件在logstash配置中合并多个jdbc输入?
- wordpress - 通过元键对 wp_query 进行优先级排序
- javascript - 如何在数据库中存储富文本
- c# - 日期范围搜索中不显示相等日期
- php - 如何使用 RegEx 将 jsfiddle URL 转换为 iframe 嵌入代码?
- mysql - MySQL where 条件基于 select 查询
- go - Gorilla/mux 中间件没有被击中
- java - MongoDB查询并选择内部对象
- android - 在我更改我的包名称后,AIDL 文件不存在或发生错误
- python - zip 迭代器和列表的区别