Inheritance in Python

Python being an Object Oriented Language supports Inheritance. Python syntax has changed over time and now it supports the use of super like most other languages. This is represented by self.
Given below is a simple example of inheritance.

class Person:

    def __init__(self, name, age,address):
        self.name = name
        self.age = age
        self.address=address

    def __str__(self):
        return "Name = " + self.name + ", Age = " + str(self.age) + ", Address = " + self.address

class Employee(Person):

    def __init__(self, name, age, address,post,salary):
        super().__init__(name,age,address)
        self.post = post
        self.salary=salary
    def __str__(self):
            return super().__str__() +  ", Post = " + self.post + ", Salary = " + str(self.salary)

x = Person("Pappu",55,"New Delhi",)

y = Employee("Pappu",420,"New Delhi","VP",420)

print(x)
print()
print(y)


Output

Name = Pappu, Age = 55, Address = New Delhi
Name = Pappu, Age = 420, Address = New Delhi, Post = VP, Salary = 420

python console

Leave a Reply