-3

How can I call the function B inside function C, by its name == str(B) only and without using self.B()?

class A:
    def B(self):
        print('sth')
    def C(self):
        # I want to call function self.B() in here by its name which is str(B)

The reason why I want to do that is:

class A:
    def C(self, person):
        if person == "John":
           self.John()
        elif person == "Ben":
           self.Ben()
    def John(self):
        print("I am john")
    def Ben(self):
        print("I am Ben")
A("John").C()

Because the person variable must be a string, I want to run the corresponding function of the parameter: person, if I can call the function by its name by some way, I don't need to add the additional if and elif condition in def C.

tung
  • 1
  • 2
  • 1
    Have you read e.g. https://stackoverflow.com/questions/2612610/how-to-access-object-attribute-given-string-corresponding-to-name-of-that-attrib? – jonrsharpe Mar 21 '22 at 13:49

1 Answers1

0

As already indicated in the comments to the original question, you need to access the methods on the instance. For instance:

class A:
    def C(self, person):
        try:
            getattr(self, person)()
        except AttributeError:
            print(f'there is no method for `{person}` in the A class')
        
    def John(self):
        print("I am john")
        
    def Ben(self):
        print("I am Ben")
        
A().C('John')
I am john

A().C('Daniel')
there is no method for `Daniel` in the A class

Although it is legit to wonder why you would want to implement such a programming pattern, getattr is there exactly for similar purposes. Still, I agree with the comments that without a better explanation, this is a programming pattern one should avoid.

deponovo
  • 928
  • 5
  • 19
  • thank you so much, that's what I am looking for, may I ask what if there are arguments in John, for example: John(self, age), what should I change in getattr(self, person)? – tung Mar 21 '22 at 15:53
  • You would need a couple more things. Please read more about args and kwargs usage in python. It would be a long story for a comment. Maybe you could start in this [SO](https://stackoverflow.com/questions/3394835/use-of-args-and-kwargs). If this answers your question, please mark it as so. – deponovo Mar 21 '22 at 20:29