Python Inheritance
A class can inherit the attributes of a super-class. This is one of the features of
object-oriented programming, where a more specialized class can be defined that uses the
attributes (functions and variables) of a super-class and extends the behavior of the
super-class. By using a super-class, you can avoid repeating common attributes of "like"
classes but also add or override behaviors of the super-class. It also common to use the
term "derived" - in the example below, Student
and Teacher
are
derived from Person
.
In this example, Person
is the super-class and contains the first and last
name variables which are common information about Teacher
and
Student
.
Example
class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def info(self): print(self.firstname, self.lastname) class Student(Person): def __init__(self, fname, lname, grade): Person.__init__(self, fname, lname) self.grade = grade def info(self): print(self.firstname, self.lastname, 'has a grade of', self.grade) class Teacher(Person): def __init__(self, fname, lname, course): Person.__init__(self, fname, lname) self.course = course def info(self): print(self.firstname, self.lastname, 'teaches', self.course) student = Student('Jane', 'Hirshfield', 'A+') teacher = Teacher('Emily', 'Dickinson', 'poetry') student.info() teacher.info()
Output
Jane Hirshfield has a grade of A+ Emily Dickinson teaches poetry
Notes
It is common practice to put the super-class initialization as the first statement in the
sub-class' __init__
function.
One can also use the super() function instead of explicitly declaring the class name. When
using super()
, the self parameter is also removed.
Example
class Student(Person): def __init__(self, fname, lname, grade): super().__init__(fname, lname) self.grade = grade def info(self): print(self.firstname, self.lastname, 'has a grade of', self.grade) class Teacher(Person): def __init__(self, fname, lname, course): super().__init__(fname, lname) self.course = course
Lastly, the hierarchy of the class structure is not limited to just a class and its super-class. A class can be derived from a super-class, which in turn is derived from a super-super-class, etc.