user3558409
user3558409

Reputation: 99

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

Upvotes: 2

Views: 20625

Answers (1)

user3159253
user3159253

Reputation: 17455

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

Upvotes: 3

Related Questions