Can a base class know if a method has been overridden?

Steven Bethard steven.bethard at gmail.com
Mon Sep 24 15:19:49 EDT 2007


Ratko wrote:
> I was wondering if something like this is possible. Can a base class
> somehow know if a certain method has been overridden by the subclass?

You can try using the __subclasses__() method on the class::

     >>> def is_overridden(method):
     ...     for cls in method.im_class.__subclasses__():
     ...         func = cls.__dict__.get(method.__name__)
     ...         if func is not None and func != method.im_func:
     ...             return True
     ...     return False
     ...
     >>> class A(object):
     ...     def foo(self):
     ...         return 'A.foo'
     ...     def bar(self):
     ...         return 'A.bar'
     ...
     >>> class B(A):
     ...     def foo(self):
     ...         return 'B.foo'
     ...
     >>> is_overridden(A.foo)
     True
     >>> is_overridden(A.bar)
     False

Given a method from the base class, is_overridden gets the base class, 
and then looks through every subclass of that class. If the function 
object for the subclass is ever different from that of the base class, 
then the base class's method must have been overridden.

STeVe



More information about the Python-list mailing list