Using function's name to call the function inside a class in Python
Question:
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?
Answers:
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.
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?
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.