如何从不在该类内部的类中运行 Python 中的函数

问题描述 投票:0回答:1

我有这个示例代码: (注意:这不是我正在使用的真实代码,但它达到了目的。)

def test():
    print("Test Function Ran")

class example():
    def init(self, funct):
        self.funct=funct

    def run_func(self):
        funct() 

e = example(test)
e.run_func()

我希望它像在线程模块及其目标参数中一样工作,但在这种情况下不起作用..

我也尝试过 lambda、*args 和 **kwargs(这不是我想使用的),但都不起作用。

python python-3.x module python-module
1个回答
0
投票

‘run_func’中的 funct() 未定义

你必须将其称为 self.funct() ,如下所示

def test():
    print("Test Function Ran")

class example():
    def __init__(self, funct):
        self.funct=funct

    def run_func(self):
        self.funct()

e = example(test)
e.run_func()

现在可以了

© www.soinside.com 2019 - 2024. All rights reserved.