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

2 投票
1 回答
20622 浏览
提问于 2025-04-18 03:40

我有点困惑,为什么这段代码不管用。在 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 个回答

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

撰写回答