我如何用列表调用特定函数
how I can call specefic function with list
我有这个 class 用于来自 post class 和 运行 的调用函数
class getitem(post):
def item_list(self):
item=[self.X(),self.A(),self.D(),self.I(),self.S(),self.V()]
return item
当我 运行 下面的代码时,我得到 运行 项
中的所有函数
p=getitem()
d=[]
print(p.item_list())
我怎样才能运行特定的功能?
换句话说:
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())
你能帮帮我吗
使用eval()输入字符串执行函数。通过这种方式,您可以获取返回值并使用给定代码使用 dict.
执行函数
或者您可以简单地通过列表的索引对函数进行 eval()
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))
我有这个 class 用于来自 post class 和 运行 的调用函数
class getitem(post):
def item_list(self):
item=[self.X(),self.A(),self.D(),self.I(),self.S(),self.V()]
return item
当我 运行 下面的代码时,我得到 运行 项
中的所有函数p=getitem()
d=[]
print(p.item_list())
我怎样才能运行特定的功能? 换句话说:
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())
你能帮帮我吗
使用eval()输入字符串执行函数。通过这种方式,您可以获取返回值并使用给定代码使用 dict.
执行函数或者您可以简单地通过列表的索引对函数进行 eval()
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))