我有這個類用于從 post 類呼叫函式并運行它們
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())
你能幫助我嗎
uj5u.com熱心網友回復:
使用 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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/424866.html
標籤:python-3.x 功能 班级
上一篇:用戶函式回傳查詢并插入
