Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python how to call function base on different input value in a class?

I have a class with multiple functions. Given an id outside the class, is it possible to call a function based on the id value?

For example,

if id = 1, run fun1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if id = 2, run fun2

class functions:
    def fun1(self, para1, para2, para3):
        pass
    def fun2(self, para1, para2, para3):
        pass
    ·
    ·
    ·

To be more precise, I’d like to call these functions in such a way.
Here in another class

id = x
fun(x, para1, para2, para3)

Then fun(x, para1, para2, para3) will call different fun in the functions class base on x

>Solution :

Use a dictionary to map the ID to a method.

func_map = {1: functions.fun1, 2: functions.fun2}
f = functions()
id = int(input("Enter function id:"))

if id in func_map:
    params = input("Enter parameters separated by space:").split()
    func_map[id](f, *params)
else:
    print("Invalid function")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading