user3558409 user3558409 - 1 month ago 8
Python Question

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

Answer

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