Search code examples
pythonoopmethodssuperclass

How to define a superclass-only method?


The snippet:

class Base:                                                                     
    def superclass_only(self):
        return 'yes'


class Foo(Base):
    pass


foo = Foo()
>>> foo.superclass_only()
yes

# Expection is to raise error
>>> foo.superclass_only()
traceback 
...
AttributeError: 'Foo' object has no attribute 'superclass_only'

How can I do if I just want to define a superclass-only method?


Solution

  • You can wrap the superclass-only method with a decorator function that validates the current instance's class name against the method's class name, which can be derived from the method's __qualname__ attribute:

    def superclass_only(method):
        def wrapper(self, *args, **kwargs):
            if self.__class__.__name__ != method.__qualname__.split('.')[-2]:
                raise NotImplementedError
            return method(self, *args, **kwargs)
        return wrapper
    

    so that with:

    class Base:
        @superclass_only
        def method(self):
            return 'yes'
    
    class Foo(Base):
        pass
    

    Calling Base().method() returns 'yes', while calling Foo().method() raises NotImplementedError.

    Demo: https://replit.com/@blhsing/SpringgreenHonorableCharacters