我正在尝试让不同的“地点”类可以指向彼此的文本冒险。让两个类互相引用
例如,我有一个Manager
类,每个地方都有一个引用。然后我有一个Home
班,和一个Club
班,通过经理提及彼此。问题是由于循环引用我无法实例化它们。
下面是我如何解决它,但它很丑,因为我必须在方法内部创建places
成员,而不是__init__
。
class Manager:
def __init__(self):
self.home = Home(self)
self.club = Club(self)
class Home:
def __init__(self, manager):
self.places = {}
self.manager = manager
def display_plot_and_get_option (self):
print "where do you want to go?"
return 'club' #get this from user
def get_next_place(self, place_name):
self.places = { #THIS IS THE BAD PART, which should be in __init__ but can't
'home':self.manaer.home
'club':self.manaer.club }
return self.places[place_name]
class Club:
#similar code to Home
pass
manager = Manager()
while (True):
place_name = manager.current_place.display_plot_and_get_option()
manager.current_place = manager.current_place.get_next_place(place_name)
在C++中我会设置在构造函数,它应该是我的字典了,它将使用Manager
的home
或club
成员的指针,因为我只希望每个地方的1个实例。我如何在Python中做到这一点?
编辑:扩展的代码示例
你在这里模拟什么?为什么家有一个俱乐部的参考?经理的职责是什么? –
当你玩游戏时,有一个主循环在当前位置上调用'display_plot_and_get_option'。然后它将结果传递给上面的'get_next_place'方法,该方法返回下一个地方。经理只是拥有地点和其他“全局”变量,如玩家的名字。 – CornSmith
是否有必须拥有引用其他类的实例的管理器类? – thikonom