Search code examples
pythonpolymorphismintrospection

How can I tell what class in the polymorphic hierarchy contains the method I'm about to call?


If I have:

class A():
    def f(self):
        print("running function, f from class A")
class B(A):
    def __init__(self):
        A.__init__(self)
    def f(self):
        print("running function, f from class B")

and I make an instance of class B and call f on it, we all know we'll see the message about "from class B." But is there a way for me to inspect my object and make sure my sub-class has overridden my method? Something like:

obj = B()
assert(not obj.f.livesIn(A))

Solution

  • If you want to force the child class to override, you can raise NotImplementedError().

    Doing the inspection is possible too... And I see unutbu just posted an example, so I won't repeat it. :)