Simple_coder
Simple_coder

Reputation: 11

Call an object function from a dictionary

What I need is to take 2 arguments from input: one instance of a class, a method of that class. the second step is to call the instance method from a dictionary that contains all methods of that class. I tried with this but it says that methods are not defined

class foo:
    def __init__(self, name):
        self.name = name

    def namePrinter(self):
        print(self.name)

    def age(self, age = 25):
        self.age = age

    def birth_year(self, this_year = 2022):
        self.birthYear = this_year - self.age
    
    
funcs = {
    'print' = namePrinter,
    'age' = age,
    'year' = birth_year
}

luca = foo(luca)
mario = foo(mario)
alberto = foo(alberto)

def funCaller():
    person = input('what foo do you want')
    func = input('what func do you want to call')
    person.funcs[func]

Upvotes: 0

Views: 621

Answers (1)

Maurice Meyer
Maurice Meyer

Reputation: 18106

You need a mapping for the persons and getattr to get a reference to function of each Person's instance:

class foo:
    def __init__(self, name):
        self.name = name

    def namePrinter(self):
        print(self.name)

    def age(self, age=25):
        self.age = age

    def birth_year(self, this_year=2022):
        self.birthYear = this_year - self.age


names = ['luca', 'mario', 'alberto']
persons = {name: foo(name) for name in names}
funcs = {'print': 'namePrinter', 'age': 'age', 'year': 'birth_year'}


def funCaller():
    #person = input('what foo do you want')
    person = 'luca'
    #func = input('what func do you want to call')
    func = 'print'

    inst = persons.get(person, None)
    if inst is None:
        print(f"{person} not found")
        return

    realFunc = funcs.get(func, None)
    if not realFunc:
        print(f"{func} not found")
        return

    getattr(inst, realFunc)()


funCaller()

Out:

luca

Upvotes: 2

Related Questions