本文介绍了从 Python 2.7 中的另一个类方法调用一个类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑为什么此代码不起作用.对于 room_instance = self.startRoom() 我得到错误:

I'm confused why this code won't work. For room_instance = self.startRoom() I get the error:

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

推荐答案

当您使用 eng = Engine('Corridor') 时,您将 'Corridor' 作为字符串传递.要访问类 Corridor,您应该使用 globals()['Corridor']

when you use eng = Engine('Corridor') you pass 'Corridor' as a string. To access class Corridor you should use 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 可能定义在其他模块等中.所以我建议如下:

But actually it's a rather fragile construction because Corridor may be defined in other module etc. So I would propose the following:

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

这篇关于从 Python 2.7 中的另一个类方法调用一个类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 09:45