[問題] class中,如何依照傳入的method name作為

看板Python作者 (Talent)時間3年前 (2020/12/17 15:56), 3年前編輯推噓0(002)
留言2則, 1人參與, 3年前最新討論串1/1
請問大家,如下程式碼,從main.py呼叫TestClass時,可以傳method name當作參數名稱,並直接執行該method嗎? 因為類別中如果要呼叫本身的method,需要以self.test1_func()呼叫. 不知道是否有其他方式或是方向可以建議,先感謝大家! PS: 手機排版,若不方便閱讀,請見諒! *** main.py *** from test_class import TestClass TestClass(p1='test_p1', p2='test_p2', func=test1_func) *** test_class.py *** class TestClass: def __init__(self, func, **less): self.p1 = kwds.get('p1') self.p2 = kwds.grt('p2') func() def test1_func(self): return 'test1', self.p1 ----- Sent from JPTT on my iPhone -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.141.147.139 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1608191779.A.67E.html

12/17 19:04, 3年前 , 1F
import inspect
12/17 19:04, 1F
謝謝,我會查詢關鍵字研究看看!

12/17 20:06, 3年前 , 2F
或直接用依賴注入
12/17 20:06, 2F
※ 編輯: Talent14 (223.141.147.139 臺灣), 12/18/2020 08:03:32
文章代碼(AID): #1VsmyZP- (Python)