【发布时间】:2018-08-03 09:24:34
【问题描述】:
我试图将值从getattr 传递给另一个class Map(),但它仍然告诉我引擎类中没有这个参数。问题是我如何将属性传递给类 Map?它一直在寻找class Engine() 中的属性。
class Engine(object):
def __init__(self,start):
self.map = start
self.quips = [
"You died. You kinda suck at this.",
"Your mom would be proud. If she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this."
]
def death(self):
print (self.quips[randint(0,len(self.quips) - 1)])
exit(1)
def play(self):
next = self.map
while True:
print ("\n------------------")
# Trying to get attribute of object and pass to class Map.
Map = getattr(self, next)
next = Map()
class Map():
def __init__(self, next):
self.map = next
def central_corridor(self):
print ("The Gothons of planet Percal #25 have invaded your ship and destryoed")
if action == "shoot!":
print ("Quick on the draw you yank out your blaster and fire)
return 'death'
elif action == 'tell a joke':
print ("Lucky for you they made you learn Gothon insults in the academy")
return 'Go to bridge'
def go_to_bridge(self):
print ("You burst onto the Bridge with the neutron destruct bomb")
a_game = Engine("central_corridor")
a_game.play()
追溯
Traceback (most recent call last):
File"c:\Learn_Python_In_the_hard_way\SourceCode\E42_Class_Execrise.py", line 175, in <module> a_game.play()
File "c:\Learn_Python_In_the_hard_way\SourceCode\E42_Class_Execrise.py", line 27, in play Map = getattr(self, next)
AttributeError: 'Engine' object has no attribute 'central_corridor'
【问题讨论】:
-
您遇到的错误的完整追溯是什么?我猜它与
next = Map()有关,您尝试在没有参数的情况下初始化Map,但需要next参数。 -
您在代码中哪里看到了
getattr()调用?如果您需要任何帮助,请发布正确的 MCVE 和完整的错误消息和回溯。 -
对不起,我把我的另一个版本放在这里。我又更新了。
-
您的代码中有很多错误,您没有在此处关闭字符串: print ("Quick on draw you yank out your blaster and fire),play 方法写得不好,您应该重新考虑你的代码有点。
-
好的,你需要决定你存储玩家位置的位置(大概是地图中的状态变量,而不是引擎)。 1)
Engineclass 不需要知道玩家在哪里,只要他们是活着还是死了(他们携带什么,他们的能量水平是多少,得分等)。所以尝试用Engine("central_corridor")初始化东西是没有意义的。Engine类不需要知道如何 来初始化Map的实例。 2) 那么如何编写Map类,使其自身将其位置初始化为“central_corridor”? 2b)位置应该存储为数据成员,而不是方法