Schilcote
Schilcote

Reputation: 2394

Check if an instance has overridden a superclass method or not in Python

I'm writing a UI library that is designed for keyboard-navigable interfaces. It has a feature where it can automatically "autocomplete" the links that determine which button the highlight moves to from any given button when the end-user presses an arrow key. Obviously this system needs to know if the library user has already specified where the link should go, or if new behavior has been specified to happen when an arrow key is pressed.

I was thinking I could just have On{Up/Down/Left/Right}ArrowKeyPressed methods, whose default is to switch highlight to self.{Up/Down/Left/Right}Link, and so if self.___Link == None and On____ArrowKeyPressed has not been overridden, the library can safely assume that it is in charge of setting that link for that button.

Is there a reliable way of detecting if an object is using its default superclass method or not? Would thebutton.OnUpArrowKeyPressed is Button.OnUpArrowKeyPressed work in all cases?

Upvotes: 3

Views: 1746

Answers (1)

Ethan Brews
Ethan Brews

Reputation: 131

You can check if a class has overridden a function by comparing the functions.

class A:
    def ping(self):
        print("pong")

class B(A):
    def ping(self):
        print("overridden")

class C(A):
    pass
    # Not Overridden

A.ping == B.ping  # False
A.ping == C.ping  # True

When I tested this it did not work when comparing the methods in the objects

a = A()
b = B()
c = C()

a.ping == b.ping  # False
a.ping == c.ping  # False

If you need to compare methods in objects you can use

a.__class__.ping == c.__class__.ping  # True

Upvotes: 6

Related Questions