Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Abstract Method With It's own __init__ function [duplicate]

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?

like image 657
user2694306 Avatar asked May 28 '15 18:05

user2694306


People also ask

Can abstract class have Init method in Python?

Introduction to Python Abstract Classes In object-oriented programming, an abstract class is a class that cannot be instantiated. However, you can create classes that inherit from an abstract class.

Can abstract method be initialized?

We cannot instantiate an abstract class in Java because it is abstract, it is not complete, hence it cannot be used.

Can a class have 2 abstract methods in Python?

Note the abstract base class may have more than one abstract methods. The child class must implement all of them failing which TypeError will be raised.

How do you overwrite an abstract method?

A non-abstract child class of an abstract parent class must override each of the abstract methods of its parent. A non-abstract child must override each abstract method inherited from its parent by defining a method with the same signature and same return type. Objects of the child class will include this method.


1 Answers

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

class DietPizza(BasePizza):
    def __init__(self):
        super().__init__()
        self.lastname = "Last Name"
like image 102
Martijn Pieters Avatar answered Sep 17 '22 23:09

Martijn Pieters