0

Maybe this is a bit funky, but I want to pass a callable instance method as a default variable to an instance method of the same class.

from typing import Callable

class Person:

    def __init__(self, name):
        self.name = name

    def say_hi(self):
        print("Hello, my name is", self.name)

    def greet(self, func: Callable=say_hi):
        func()

p = Person("Guido")
p.greet()

With the above solution self is not passed to the instance method. Replacing func: Callable=say_hi with func: Callable=self.say_hi and self is not yet defined.

1
  • if you know it is an instance method? why are you passing it? You can access it inside greet like self.say_hi, if you still insist then you can d0 p.greet(p.say_hi) Commented Sep 10, 2021 at 8:46

1 Answer 1

3

You can do assignment in the function itself:

def greet(self, func: Callable = None):
    func = self.say_hi if func is None else func
    func()

Suggestion by @blhsing in the comments below is to use this (tho being explicit is kinda better than implicit, but this will work too):

func = func or self.say_hi
Sign up to request clarification or add additional context in comments.

1 Comment

Or func = func or self.say_hi if you like it shorter. (Too bad there's no equivalent of the ||= operator of Ruby in Python.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.