-3

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

class A:
    def name_dispatcher(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 I want to aviod something in 'def name_dispatcher' when the number of parameters get largers, if I can call the function by its name, I don't need to add the additional if and elif condition as def name_dispatcher. Will the method better than if-else? Or is a there any readable and efficient method to do so?

tung
  • 75
  • 5
  • 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
  • [That question](https://stackoverflow.com/questions/3521715/call-a-python-method-by-name) seems to be a better duplicate than the current one. – Tsyvarev Oct 09 '22 at 03:19

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
  • 1,114
  • 7
  • 23
  • 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