Python Class Inheritance: How to initialize a subclass with values not in the parent class
Create a custom initializer on the sub-class and then call the parent class's initializer via super
:
class Person(Entity):
def __init__(self, state, name, age, gender):
self.gender = gender
super(Person, self).__init__(state, name, age)
Transitionally, it looks like versions of Py 3.x (not sure which ones) allow this terse version of super()
:
def __init__(self, state, name, age, gender):
self.gender = gender
# Prototype initialization 3.x:
super().__init__(state, name, age)
Been experimenting with SQLAlchemy models using dataclasses, so when I zipped on by looking at all things Python inheritance, I felt this might extend the answer:
from dataclasses import dataclass
@dataclass
class Entity():
state: str
name: str
age: int
@dataclass
class Person(Entity):
gender: str
def describe(self):
print("State: {state}, Name: {name}, Age: {age}, Gender: {gender}"
.format(state=self.state, name=self.name, age=self.age, gender=self.gender))
man = Person("human", "humanname", 21, "cisgendered")
man.describe()