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?
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.
We cannot instantiate an abstract class in Java because it is abstract, it is not complete, hence it cannot be used.
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.
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.
Your BasePizza.__init__
is a concrete method; just invoke it using super()
:
class DietPizza(BasePizza):
def __init__(self):
super().__init__()
self.lastname = "Last Name"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With