0

I know this is stupid, but I don't know. I can't figure out method as decorator. I have 2 classes: 1 Button and 1 child Button. I want to play a sound when the button is clicked. So there is a call function in the Button class.

class Button:
    def __call__(self):
        print("play")

Now in the child class, I want the button to do something, but I still want to play the sound. If I override the call function, the play sound part will disappear.

class ChildButtonn(Button):
    def __call__(self):
        # button things but the sound is gone
        # I need to write the play thing again here
        print("play")

So how to do that?

3 Answers3

2

Call the parent class' __call__ method:

class ChildButtonn(Button):
    def __call__(self):
        super().__call__()
        print("specific actions for ChildButtonn")
        ...

FWIW, are you sure you need to use __call__? unless dealing with a very specific requirement (eg when using the object as a callable callback), using __call__ usually end up with unreadable code (who knows what ChildButtonn()() might or might not do?). It is usually better to use a named method, eg ChildButtonn().click().

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
1
class ChildButtonn(Button):
    def __call__(self):
        # button things but the sound is gone
        # I need to write the play thing again here
        super().__call__() #will __call__ parent class method

You can use 'super' to use parent class.

1

call the parent class __call__ inside the ChildButton's __call__ function using super function

class Button:
    def __call__(self):
        print("play")

class ChildButtonn(Button):
    def __call__(self):
        super().__call__()
        print("play")


c = ChildButtonn()
c()
Sidharth Mudgil
  • 1,293
  • 8
  • 25