gpt4 book ai didi

python - 使两个类互相引用

转载 作者:行者123 更新时间:2023-11-28 21:56:53 24 4
gpt4 key购买 nike

我正在尝试进行文本冒险,其中不同的“地点”类可以指向彼此。

例如,我有一个 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++ 中,我会在构造函数中设置我的字典,它应该在的位置,它会使用 Managerhome 的指针club 成员,因为我只想要每个地方的 1 个实例。我如何在 Python 中执行此操作?

编辑:扩展代码示例

最佳答案

您可以只拥有一个包含引用的字典,并直接从管理器(它不应该真正命名为管理器,因为它现在不用于该目的)实例调用方法。

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)

关于python - 使两个类互相引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20726305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com