如何在Python中将类成员函数的默认参数设置为同一类中的另一个成员函数

sky*_*ree 0 python class

我想要做的是:将foo函数指针bar作为默认参数传递给函数。但这是不允许的。如何实施?

class Klass ():
    def __init__(self):
        print('init')

    def foo(self):
        print('foo')

    def bar(self, func=self.foo): # error here
        func()
        print('bar')
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 5

默认值在定义函数时计算一次,而不是每次调用时计算。所以它不能引用其他参数或其他动态数据。

您需要在函数中分配它。

def bar(self, func = None):
    if func is None:
        func = self.foo
    func()
    print('bar')
Run Code Online (Sandbox Code Playgroud)