作者Talent14 (Talent)
看板Python
标题[问题] class中,如何依照传入的method name作为
时间Thu Dec 17 15:56:17 2020
请问大家,如下程式码,从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://webptt.com/cn.aspx?n=bbs/Python/M.1608191779.A.67E.html
1F:→ LP9527: import inspect 12/17 19:04
谢谢,我会查询关键字研究看看!
2F:→ LP9527: 或直接用依赖注入 12/17 20:06
※ 编辑: Talent14 (223.141.147.139 台湾), 12/18/2020 08:03:32
3F:→ zerof: 直接传 method 12/26 06:54
4F:→ tsaiminghan: 用getattr 12/26 09:01