Search code examples
pythonpython-3.xinheritanceabstract-classabc

How to implement a constructor for an abstract base class?


I am trying to write a base abstract class that has some properties that will be initialized using a constructor. So far I have this:

from abc import ABC, abstractmethod

class A(ABC):
    def __init__(self, n, *params):
        self.n = n
        self.initialize_params(*params) #I want to do this in all subsclasses of A
    def initialize_params(self, *params)
       pass
    @abstractmethod
    def do(self):
        pass

class B(A):
    def __init__(self, m, n, *super_params):
        self.m = m
        super(A, self).__init__(n, *super_params)
    def do(self):
        print("this is B")

But this will throw TypeError because of instantiation of A in __init__ of B. What is the correct way of doing this?


Solution

  • You seem to have a couple of mistakes:

    from abc import ABC, abstractmethod
    
    class A(ABC):
        def __init__(self, n, *params):
            self.n = n
            self.initialize_params(*params) #I want to do this in all subsclasses of A
        def initialize_params(self, *params):
            pass
        @abstractmethod
        def do(self):
            pass
    
    class B(A):
        def __init__(self, m, n, *super_params):
            self.m = m
            super().__init__(n, *super_params)  # correct way to use super() to call init
        def do(self):
            print("this is B")
    
    
    b = B(1,2)
    b.do()
    

    Note that you missed self. infront of initialize_params() and you didn't seem to be using super() correctly.