python - 创建类的实例时可以调用类的实例吗?
问题描述
我正在尝试编写文本冒险。我为房间内的对象创建了一个类。在下面的代码中,
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)
我希望立即检测门是打开还是关闭,并相应地更改描述。我知道上面的代码肯定是错误的,但是有没有办法呢?
解决方案
我不是 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)
您应该看到正确的输出值。
推荐阅读
- java - 从私钥模数和私有指数中获取 RSA 公钥
- android - Play 商店 - 打开托管 google play 时,内部应用共享和内部测试不起作用
- php - 用具有相同键的不同关联数组的值替换关联数组的键
- reactjs - 如何使用 react-image-upload 依赖项将图像上传到数据库?
- mysql - 没有 id 的 Laravel 质量分配(自动增量)
- javascript - 在 Angular 应用程序中打印 PDF 文件而无需预览
- mysql - 具有多个 AND OR 的 MySQL Case 语句不能嵌套
- facebook - 无法通过 Facebook API 访问潜在客户详细信息
- mysql - 使用 SQL 从数据库中选择 2 个用户之间的对话
- python - 如何创建一个包含 16 个元素的列表?