How to detect method overloading in subclasses in python?

If you want to check for an overridden instance method in Python 3, you can do this using the type of self:

class Base:
    def __init__(self):
        if type(self).method == Base.method:
            print('same')
        else:
            print('different')

    def method(self):
        print('Hello from Base')


class Sub1(Base):
    def method(self):
        print('Hello from Sub1')


class Sub2(Base):
    pass

Now Base() and Sub2() should both print “same” while Sub1() prints “different”. The classmethod decorator causes the first parameter to be bound to the type of self, and since the type of a subclass is by definition different to its base class, the two class methods will compare as not equal. By making the method an instance method and using the type of self, you’re comparing a plain function against another plain function, and assuming functions (or unbound methods in this case if you’re using Python 2) compare equal to themselves (which they do in the C Python implementation), the desired behavior will be produced.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)