0

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.

2
  • I am looking for a way to modify method B inside the class, in order to make object p convenience to use? Such as just pass the name of fn A1 (or through a string) to call A or modify A1 name leading/trailing with some __? I have many fn name to pass in. I had read How do I pass a method as a parameter in python and Python: pass method as argument in function before this post, but not get an direct answer. Commented Nov 19, 2015 at 15:20
  • I updated my answer with a way to pass the name of A1 as a string. Commented Nov 19, 2015 at 22:04

1 Answer 1

3
>>> 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.