【问题标题】:Access Another Class from a Dictionary within a Class从类中的字典访问另一个类
【发布时间】:2018-10-03 14:25:05
【问题描述】:

我正在尝试通过使用类 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

【问题讨论】:

  • 您忘记从dictionary 返回items。此外,enter 方法不会返回任何内容,因此items 中的所有内容都将是None。您可能想重新审视 Python 函数的工作原理
  • 另外,dictionary 缺少参数或 @staticmethod 装饰器。无论如何,为什么dictionary 不只是...字典?
  • 我正在尝试使用基本上所有内容的类创建一个游戏(这对我来说似乎很愚蠢,但它是 Learn Python the Hard Way ex43 练习的一部分)。我假设它,所以我习惯于理解继承是如何工作的等等,但老实说,它只是让一切变得超级复杂。我尝试添加 return 以输入方法和项目,但我得到了相同的结果。我已经尝试解决这个问题 3 天了,哈哈……我已经完全不知道发生了什么
  • FWIW,SO Python 聊天室常客do not recommend LPTHW。如果它对你有用,那就太好了,但请注意这本书有几个问题。
  • 您没有正确使用类。事实上,正确地编写这样的游戏非常、非常困难。对于初学者来说,这是一个可怕的练习。您可能应该找到一个更好的练习来解决 - 也可能找到一个合适的 OOP 教程。

标签: python class dictionary


【解决方案1】:
  • 您忘记从dictionary 返回items。此外,enter 方法不会返回任何内容,因此items 中的所有内容都将是None。您可能想重新审视 Python 函数的工作原理。
  • 每次调用Rooms.dictionary 时重新创建items 似乎是一种浪费。您可以使用类实例。
  • 正如 timgeb 在 cmets 中所写,您忘记了方法中的 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

【讨论】:

  • 感谢 DeepSpace!这行得通,我必须研究这些 classmethods 和 staticmethods 正在做什么才能使这项工作。非常感谢!
  • 这个答案中没有什么是错误,但它当然也不是 OOP 的正确应用。只有一个静态方法的类不应该是一个类。 3 个要点是有用的信息,但代码本身是值得一票的。
  • 哈哈,是的,Aran-Fey 将其剥离以使其易于调试(只是想知道如何使用字典直接访问类中的方法)。但是是的,我认为在本练习的其余部分中删除课程,请不要对我投反对票:D
【解决方案2】:

你应该让函数首先返回字典

return items

之后字典需要修改:

items = {
         'room1': 'Castle.enter()',
         'room2': 'Door.enter()'
        }

如果您不期望输出,则需要使用exec() 函数,如果您期望这样的输出,则需要使用eval()

exec(Rooms.dictionary()['room1'])

【讨论】:

  • 不,你不需要在这里使用execeval
猜你喜欢
  • 2012-12-27
  • 2012-05-18
  • 2016-11-26
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 2020-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多