python - 从类中的字典访问另一个类
问题描述
我正在尝试通过使用类 Rooms() 中的字典来访问类 Castle()。
我不明白如何只访问 room1 或 room2 而不会意外访问两者?
我已经用尽了我能想到的每一条途径,但我确信它可能是我想念的非常简单的东西。提前致谢!
class Castle():
def enter():
print("This is castle")
class Door():
def enter():
print("This is door")
class Rooms():
def dictionary():
items = {
'room1': Castle.enter(),
'room2': Door.enter()
}
Rooms.dictionary()['room1']
它打印出来:
This is castle
This is door
Traceback (most recent call last):
File "C:\Users\James\Python\03_ZedShaw\test.py", line 22, in <module>
Rooms.dictionary()['room1']
TypeError: 'NoneType' object is not subscriptable
解决方案
- 你忘了
items
从dictionary
. 此外,enter
方法不会返回任何内容,因此无论如何items
都会返回任何内容。None
您可能想重新审视 Python 函数的工作原理。 items
每次Rooms.dictionary
调用都重新创建似乎是一种浪费。您可以使用类实例。- 正如 timgeb 在评论中所写,您忘记了
self
方法或@staticmethod
装饰器中的参数。
class Castle:
@staticmethod
def enter():
return "This is castle"
class Door:
@staticmethod
def enter():
return "This is door"
class Rooms:
items = {'room1': Castle.enter(),
'room2': Door.enter()}
@classmethod
def dictionary(cls, key):
return cls.items[key]
print(Rooms.dictionary('room1'))
# This is castle
print(Rooms.dictionary('room2'))
# This is door
此时您实际上并不需要Rooms.dictionary
:
class Rooms:
items = {'room1': Castle.enter(),
'room2': Door.enter()}
print(Rooms.items['room2'])
# This is door
推荐阅读
- python - 退出数据库时密码格式错误
- html - 微调器未显示在引导程序 4.0.0 中
- javascript - 在服务器上设置 HTML 输入无效
- flutter - 在 Flutter 的底部导航栏上显示抽屉
- swift - 不推荐使用未标记尾随闭包的向后匹配...有什么方法可以使其静音,而不是停止使用尾随闭包?
- google-cloud-platform - 删除与 google 帐户关联的电子邮件后,您的 google 帐户和 google 项目会发生什么情况
- ios - 在 UILabel 上获取文本字符框
- sql - 更新数百万条记录 Oracle
- xslt-2.0 - 如何在 xslt 中拆分和打印值?
- swift - 为什么我的 SwiftUI VStack 没有正确对齐?