Python Abstract Method With It's own __init__ function

user2694306 picture user2694306 · May 28, 2015 · Viewed 11.6k times · Source

How can I define a __init__ function in both the base and derived abstract classes and have all self.* be available in the abstract method? For example: 

What is the proper way of utilizing functions that are imported in the base class of an abstract class? For example: in base.py I have the following:

import abc

class BasePizza(object):
    __metaclass__  = abc.ABCMeta
    def __init__(self):
        self.firstname = "My Name"

    @abc.abstractmethod
    def get_ingredients(self):
         """Returns the ingredient list."""

Then I define the method in diet.py:

import base

class DietPizza(base.BasePizza):
    def __init__(self):
        self.lastname = "Last Name"

    @staticmethod
    def get_ingredients():
        if functions.istrue():
            return True
        else:
            return False

However when I run diet.py I only have access to self.lastname. I would want DietPizza to have both self.firstname and self.lastname. How can I do this?

Answer

Martijn Pieters picture Martijn Pieters · May 28, 2015

Your BasePizza.__init__ is a concrete method; just invoke it using super():

class DietPizza(BasePizza):
    def __init__(self):
        super().__init__()
        self.lastname = "Last Name"