【问题标题】:How to set a default parameter of a class member function as another member function within the same class in Python [duplicate]如何在Python中将类成员函数的默认参数设置为同一类中的另一个成员函数[重复]
【发布时间】: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 是的,当然。

标签: python class


【解决方案1】:

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

您需要在函数中分配它。

def bar(self, func = None):
    if func is None:
        func = self.foo
    func()
    print('bar')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多