[英]Calling a class method from another class method in Python 2.7
I'm confused why this code won't work. 我很困惑为什么这段代码行不通。 For room_instance = self.startRoom()
I get the error: 对于room_instance = self.startRoom()
我得到了错误:
'str' object is not callable.
My code: 我的代码:
class Corridor:
def enter(self):
print "Yureka. First Room!"
class Engine(object):
def __init__(self, startRoom):
self.startRoom = startRoom #sets the startRoom to 'Corridor' for the eng instance
def room_change(self):
room_instance = self.startRoom()
room_instance.enter()
eng = Engine('Corridor')
eng.room_change()
when you use eng = Engine('Corridor')
you pass 'Corridor'
as a string. 当您使用eng = Engine('Corridor')
,会将'Corridor'
作为字符串传递。 To access class Corridor you should use globals()['Corridor']
要访问类走廊,您应该使用globals()['Corridor']
class Engine(object):
def __init__(self, startRoom):
self.startRoom = globals()[startRoom] #sets the startRoom to 'Corridor' for the eng instance
def room_change(self):
room_instance = self.startRoom()
room_instance.enter()
But actually it's a rather fragile construction because Corridor
may be defined in other module etc. So I would propose the following: 但这实际上是一个相当脆弱的构造,因为可能在其他模块等中定义了Corridor
。因此,我提出以下建议:
class Corridor:
def enter(self):
print "Yureka. First Room!"
class Engine(object):
def __init__(self, startRoom):
self.startRoom = startRoom #sets the startRoom to 'Corridor' for the eng instance
def room_change(self):
room_instance = self.startRoom()
room_instance.enter()
eng = Engine(Corridor) # Here you refer to _class_ Corridor and may refer to any class in any module
eng.room_change()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.