首页 > 解决方案 > 创建类的实例时可以调用类的实例吗?

问题描述

我正在尝试编写文本冒险。我为房间内的对象创建了一个类。在下面的代码中,

self.door = Object("Door", "There is an {} door in the north.".format("closed" if self.door.openstate == False else "open"), True, False, door_text, True, False)

我希望立即检测门是打开还是关闭,并相应地更改描述。我知道上面的代码肯定是错误的,但是有没有办法呢?

标签: pythonpython-3.x

解决方案


我不是 100% 确定这是否会回答你的问题,但我认为你需要为你的门创建一个单独的类。我假设你有这样的房间课程:

class Room:

    def __init__(self):
        self.door = your_code_here

您可能需要做的是创建一个门类,例如:

class Door:

     def __init__(self, door_state):
         self.door_state = door_state

     @property
     def door_text(self):
         door_state = 'open' if not self.door_state else 'closed'
         return f"There is an {door_state} in the north"

然后你的 Room 类将如下所示

class Room:

    def __init__(self):
        self.door = Door(False)

最后,如果你运行类似的东西

r = Room()
print(r.door.door_text)

您应该看到正确的输出值。


推荐阅读