简体   繁体   English

如何在循环内定义 Python 函数并使用 *args 和 **kwargs

[英]How to define Python functions inside a loop and use *args and **kwargs

I'm trying to print a message when instance methods get called, like below.我正在尝试在调用实例方法时打印一条消息,如下所示。 I'm running into this problem , but I'm having trouble solving it in my case because all the solutions seem to require passing in specific arguments which I can't do here.我遇到了这个问题,但在我的情况下我无法解决它,因为所有解决方案似乎都需要传递特定的 arguments ,而我在这里不能这样做。

class MathLab:
    def add(self, a, b):
        print(a + b)

    def mult(self, a, b):
        print(a * b)


m = MathLab()

for method in [m.add, m.mult]:
    def tracked_method(*args, **kwargs):
        print("Running: " + method.__name__)
        method(*args, **kwargs)


    m.__setattr__(method.__name__, tracked_method)

m.add(5, 5)

Output Output

Running: mult
25

Would this help?这会有帮助吗? Add a keyword argument with a default value in order to do early binding of method (then use that keyword argument _method in place of method inside the function).添加一个具有默认值的关键字参数,以便对method进行早期绑定(然后使用该关键字参数_method代替函数内的method )。

The whole code is shown for convenience, but the only part changed from the code in the question is the tracked_method function itself.为方便起见,显示了整个代码,但问题中代码的唯一更改部分是tracked_method function 本身。

class MathLab:
    def add(self, a, b):
        print(a + b)

    def mult(self, a, b):
        print(a * b)


m = MathLab()

for method in [m.add, m.mult]:
    def tracked_method(*args, _method=method, **kwargs):
        print("Running: " + _method.__name__)
        _method(*args, **kwargs)


    m.__setattr__(method.__name__, tracked_method)

m.add(5, 5)

Gives:给出:

Running: add
10

By the way, instead of using m.__setattr__(...) , you could simply use setattr(m, ...) .顺便说一句,您可以简单地使用setattr(m, ...)而不是使用m.__setattr__(...) ) 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM