简体   繁体   中英

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM