Search code examples
pythonpython-3.xstaticabstract-classabstract-methods

How to override static abstract method of base in a subclass?


I have an abstract class with a static function that calls other abstract functions. But when I'm creating a new class and overriding abstract function still the original (abstract) function is running.

I have written an example similar to my problem. Please help. In the following example, I want to run do_something() from Main not Base.

from abc import ABC, abstractmethod

class Base(ABC):
    @staticmethod
    @abstractmethod
    def do_something():
        print('Base')

    @staticmethod
    def print_something():
        Base.do_something()

class Main(Base):
    @staticmethod
    def do_something():
        print('Main')

Main.print_something()

Output:

Base

Solution

  • Main.print_something doesn't exist, so it resolves to Base.print_something, which explicitly calls Base.do_something, not Main.do_something. You probably want print_something to be a class method instead.

    class Base(ABC):
        @staticmethod
        @abstractmethod
        def do_something():
            print('Base')
    
        @classmethod
        def print_something(cls):
            cls.do_something()
    
    class Main(Base):
        @staticmethod
        def do_something():
            print('Main')
    
    Main.print_something()

    Now when Main.print_something resolves to Base.print_something, it will still receive Main (not Base) as its argument, allowing it to invoke Main.do_something as desired.