[问题] class中,如何依照传入的method name作为

楼主: Talent14 (Talent)   2020-12-17 15:56:17
请问大家,如下程式码,从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
作者: LP9527 (ㄊㄇ抽菸都去)   2020-12-17 19:04:00
import inspect或直接用依赖注入
作者: zerof (猫橘毛发呆雕像)   2020-12-26 06:54:00
直接传 method
作者: tsaiminghan (tsaiminghan)   2020-12-26 09:01:00
用getattr

Links booklink

Contact Us: admin [ a t ] ucptt.com