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

Issue

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

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")

Answered By – Barmar

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.