【发布时间】:2019-12-15 09:44:52
【问题描述】:
我要做的是:将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')
【问题讨论】:
-
函数指针? Python 没有函数指针。无论如何,问题是
self没有定义。只需使用foo。 -
你做不到。默认值在定义函数时计算,而不是在调用时计算。
-
@juanpa 是的,但你会得到它的未绑定版本。
-
@deceze 是的,当然。