Yang
Yang

Reputation: 35

Python pass function name as argument

My goal is to write a class that should allow me to determine which method to call ( A1 or A2 ) while creating an object p. C will call B, B will call A.

def A1():
    return 'A1_g'
def A2():
    return 'A2_g'

class test:

    def __init__(self, means=None):
        self.means=means

    def A1(self):
        return 'A1'
    def A2(self):
        return 'A2'
    def B(self,A):
        new_string='methodB called '+A()
        print new_string
    def C(self):
        q=self.B(self.means)
        return q

p=test(means=A1)

p.C()

I got this output "methodB called A1_g". But I want "methodB called A1"

If I delete the top 2 fn definition, I got "NameError: name 'A1' is not defined". Want to understand how and why to achieve this.

Upvotes: 0

Views: 4176

Answers (1)

John1024
John1024

Reputation: 113814

>>> p = test(means=test().A1)
>>> p.C()
methodB called A1

Or, more concisely:

>>> test(means=test().A1).C()
methodB called A1

Alternative: passing the method name as a string

If, instead of passing the method itself, we want to pass the name of the method as a string, then we need to change method B as follows:

    def B(self,A):
        method = getattr(self, A)
        new_string='methodB called ' + method()
        print new_string

The getattr function returns the attribute of self that is named by the variable A.

Now, this can be run as follows:

>>> p = test(means="A1")
>>> p.C()
methodB called A1

Upvotes: 3

Related Questions