简体   繁体   中英

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?

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.

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