dotancohen
dotancohen

Reputation: 31491

Specify which method to call

Consider this class:

class Foo(object):

    def bar(self, name):
        return 'bar: ' + name

    def baz(self, name):
        return 'baz: ' + name

I need to tell code to run the baz method:

def run_a_method(method, name):
    f = Foo()
    f.method(name)

run_a_method('baz', 'Jeff Atwood')

This fails with the following error:

AttributeError: 'Foo' object has no attribute 'method'

What is the proper way to call the function on whatever class f is defined?

Upvotes: 0

Views: 81

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336378

First, you need to define your class correctly - don't forget the self parameter:

class Foo(object):
    def bar(self, name):
        return 'bar: ' + name
    def baz(self, name):
        return 'baz: ' + name

Then, use getattr() to access an attribute by name:

>>> a = Foo()
>>> getattr(a, "baz")("Jeff Atwood")
'baz: Jeff Atwood'

Upvotes: 2

Related Questions