Object Oriented
Inheritance
Python
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hi! I'm " + name)
class Teacher(Person):
def __init__(self, name, grade):
Person.__init__(self, name)
self.grade = grade
Classes can inherit methods and properties of another class.
In this example, the Teacher class inherits the name
property and greet()
method from the Person
class.
teacher1 = Teacher("Alice", 2)
name = teacher1.name # Alice
teacher1.greet() # Hi! I'm Alice
You need to explicitly call the Parent (Person
) Constructor from the children (Teacher
) Constructors.
Notice that we are passing self
on calling the parent constructor.
class Person:
def __init__(self, name):
self.name = name;
def greet(self):
print("Hi! I'm " + self.name)
class Teacher(Person):
def __init__(self, name):
Person.__init__(self, name)
def greet(self):
print("Hello! I am " + self.name)
def greet2(self):
Person.greet(self)
Inherited methods from a parent class can be overridden in the children's classes.
Overriding methods is more like extending the definition rather than replacing them.
teacher1 = Teacher("Alice")
teacher1.greet() # Hello! I am Alice
teacher1.greet2() # Hi! I'm Alice