简体   繁体   中英

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

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')

    
    def print_something():
        .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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM