Newbie: Changing a string to a class attribute.

Jacob H jacobsmail at gmx.net
Mon Sep 29 14:48:41 EDT 2003


Thanks everybody.

getattr(object, method)()

This solution works just fine for me. Incidentally, the reason I can't
just write object.method() is that I'm attempting to implement the
Command design pattern, like so:

class Command:
    def execute(self):
        pass

class ConcreteCommand(Command)
    def __init__(self, receiver, action):
        self.receiver = receiver
        self.action = action

    def execute(self):
        if hasattr(self.receiver, self.action):
            getattr(self.receiver, self.action)()

As can be seen, I needed a way to dynamically execute a given object
method. That's why I had to ask this question in the first place.

Thanks for the help! :)

Jake




More information about the Python-list mailing list