0

What I want to do is: Pass foo function pointer to function bar as a default parameter. But it is not allowed. How to implement it?

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

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

    def bar(self, func=self.foo): # error here
        func()
        print('bar')
skytree
  • 1,060
  • 2
  • 13
  • 38

1 Answers1

4

The default value is evaluated once, when the function is defined, not every time it's called. So it can't refer to other parameters or other dynamic data.

You'll need to assign it in the function.

def bar(self, func = None):
    if func is None:
        func = self.foo
    func()
    print('bar')
Barmar
  • 741,623
  • 53
  • 500
  • 612