我正在尝试通过在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
答案 0 :(得分:0)
items
返回dictionary
。另外,enter
方法不会返回任何内容,因此items
中的所有内容都将是None
。您可能需要重新研究Python函数的工作方式。items
时重新创建Rooms.dictionary
似乎是浪费。您可以使用类实例。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
答案 1 :(得分:0)
class Castle():
def enter():
return "This is castle"
class Door():
def enter():
return "This is door"
class Rooms():
items = {'room1': Castle.enter(),'room2': Door.enter()}
def dictionary():
return Rooms.items
测试代码:
Rooms.dictionary()
结果:
{'room1': 'This is castle', 'room2': 'This is door'}
答案 2 :(得分:-2)
您应该使函数首先返回字典
import pandas as pd
import numpy as np
np.random.seed(12)
df = pd.DataFrame(np.random.randint(1,5,(20,2500)))
df.gt(3).idxmax()
#0 0
#1 0
#2 4
#3 4
#4 1
#...
#2496 8
#2497 0
#2498 5
#2499 1
之后,字典需要更改:
return items
然后,如果您不希望输出,则需要使用items = {
'room1': 'Castle.enter()',
'room2': 'Door.enter()'
}
函数;如果您希望这样的输出,则需要使用exec()
:
eval()