Home > Net >  how I can call specefic function with list
how I can call specefic function with list

Time:02-15

I have this class for call functions from post class and run them

class getitem(post):
    def item_list(self):
            item=[self.X(),self.A(),self.D(),self.I(),self.S(),self.V()]

            return item

when I run below code then I get run all functions in item

p=getitem()
d=[]
print(p.item_list())

how I can run specific functions? in other words:

class getitem(post):
    def item_list(self,item):
            item=[self.X(),self.A(),self.D(),self.I(),self.S(),self.V()]

            return item

d=[X,I,V]
p=getitem(d)

print(p.item_list())

can you help me

CodePudding user response:

Use eval() to execute function by inputting string. In this way you can get the returned value and execute the function by a given code using dict.

Or you can simply eval() the function by index of list

class getitem():
    def itemByDict(self, i):
        item={'a':'funcA', 'b':'funcB'}
        return eval(f'self.{item[i]}()')
    def itemByList(self, i):
        item=['funcA','funcB']
        return eval(f'self.{item[i]}()')
    def funcA(self):
        print('a')
        return 1
    def funcB(self):
        print('b')
        return 2
p=getitem()
print(p.itemByDict('a'))
print(p.itemByList(0))
  • Related