B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python Inheritance with Examples | LiveCodeProgramming

Inheritance in Python

Inheritance allows one class (child) to inherit properties and methods from another class (parent). It promotes code reuse and organizes code logically.

Inheritance एक class को दूसरी class से properties और methods लेने की सुविधा देता है। यह कोड को reuse करने और structure बनाने में मदद करता है।

Advantages of Inheritance

  • Code reusability
  • Improved structure and hierarchy
  • Easy maintenance and scalability
  • Code reuse करना आसान
  • Better structure और hierarchy
  • Code को maintain और scale करना आसान
Example 1: Single Inheritance
class Employee:
    def show(self):
        print('Employee details')

class Manager(Employee):
    def display(self):
        print('Manager inherits Employee')

m = Manager()
m.show()
m.display()

Output:

Employee details
Manager inherits Employee
Example 2: Multilevel Inheritance
class Company:
    def company_info(self):
        print('Company: LiveCode')

class Employee(Company):
    def emp_info(self):
        print('Employee: Aryan')

class Manager(Employee):
    def mgr_info(self):
        print('Manager: Raj')

m = Manager()
m.company_info()
m.emp_info()
m.mgr_info()

Output:

Company: LiveCode
Employee: Aryan
Manager: Raj
Example 3: Hierarchical Inheritance
class Employee:
    def base(self):
        print('Base Employee')

class Developer(Employee):
    def dev(self):
        print('Developer Role')

class Tester(Employee):
    def test(self):
        print('Tester Role')

d = Developer()
t = Tester()
d.base()
d.dev()
t.base()
t.test()

Output:

Base Employee
Developer Role
Base Employee
Tester Role
Example 4: Multiple Inheritance
class A:
    def methodA(self):
        print('From Class A')

class B:
    def methodB(self):
        print('From Class B')

class C(A, B):
    def methodC(self):
        print('From Class C')

obj = C()
obj.methodA()
obj.methodB()
obj.methodC()

Output:

From Class A
From Class B
From Class C