我想要做的是:将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)
默认值在定义函数时计算一次,而不是每次调用时计算。所以它不能引用其他参数或其他动态数据。
您需要在函数中分配它。
def bar(self, func = None):
if func is None:
func = self.foo
func()
print('bar')
Run Code Online (Sandbox Code Playgroud)