3

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?

Schilcote
  • 2,344
  • 1
  • 17
  • 35
  • Possible duplicate of [How can a python base class tell whether a sub class has overridden its methods?](https://stackoverflow.com/questions/1776994/how-can-a-python-base-class-tell-whether-a-sub-class-has-overridden-its-methods) – kwarunek Jul 04 '17 at 21:13
  • simply use `Button.OnUpArrowKeyPressed is thebutton.OnUpArrowKeyPressed.__func__` – kwarunek Jul 04 '17 at 21:14

1 Answers1

6

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
Ethan Brews
  • 131
  • 1
  • 5
  • 3
    For instances, those are method descriptors, you can get the original back with `.__func__`, for instance `>>> a.ping.__func__ == b.ping.__func__ True` – anthony sottile Jul 04 '17 at 21:23
  • Note: to use this comparison, all classes must have the same import paths paths. Otherwise you'll have two different physical classes referencing the same logical class. See related discussion on this [thread](https://stackoverflow.com/questions/11461356/issubclass-returns-false-on-the-same-class-imported-from-different-paths) where `issubclass(B, A)` would return `False` – Addison Klinke Nov 15 '22 at 18:17