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

Raymond Hettinger python at rcn.com
Mon Sep 24 18:04:56 EDT 2007


On Sep 24, 8:23 am, Ratko <rjago... at gmail.com> wrote:
> Hi all,
>
> 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?
> I appreciate any ideas.
> Thanks,
>
> Ratko


It's not hard.  Both bound and unbound methods have an im_func
attribute pointing to the underlying function code.  So you can check
for overrides by testing whether the underlying functions are the
same:

>>> class A:
	def p(self): pass
	def q(self): pass


>>> class B(A):
	def q(self): pass


>>> b = B()
>>> b.p.im_func is A.p.im_func     # Verify that b.p runs A.p
True
>>> b.q.im_func is A.q.im_func     # Verify that b.q overrides A.q



Raymond

False




More information about the Python-list mailing list