从Python 2.7中的另一个类方法调用类方法

时间:2014-04-22 00:27:10

标签: python python-2.7

我很困惑为什么这段代码不会起作用。对于room_instance = self.startRoom(),我收到错误:

'str' object is not callable.  

我的代码:

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()

1 个答案:

答案 0 :(得分:3)

当您使用eng = Engine('Corridor')时,您将'Corridor'作为字符串传递。要访问类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()

但实际上它是一个相当脆弱的结构,因为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()