使两个类互相引用

Cor*_*ith 4 python oop

我正在尝试制作一个文本冒险,其中不同的“地点”类可以互相指向。

例如,我有一个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)
Run Code Online (Sandbox Code Playgroud)

在 C++ 中,我会在构造函数中设置我的字典,它应该在哪里,并且它将使用 或Manager成员的指针,因为我只想要每个位置的 1 个实例。我怎样才能在Python中做到这一点?homeclub

编辑:扩展代码示例

thi*_*nom 5

您可以只拥有一个保存引用的字典,并直接从 Manager(实际上不应该命名为 Manager,因为它现在不用于该目的)实例调用方法。

class Home(object):
    pass

class Club(object):
    pass

PLACES = {
   'home': Home(),
   'club': Club()
}

class Manager(object):
    def display_plot_and_get_option(self):
        return raw_input('Where do you want to go?')
   def get_next_place(self, place_name):
        return PLACES[place_name]

m = Manager()
while 1:
    place_name = m.display_plot_and_get_option()
    m.get_next_place(place_name)
Run Code Online (Sandbox Code Playgroud)