首页 > 解决方案 > 从类中的字典访问另一个类

问题描述

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

标签: pythonclassdictionary

解决方案


  • 你忘了itemsdictionary. 此外,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

推荐阅读