Python Inheritance Concepts
Python Inheritance Concepts
1. Basic Inheritance
Inheritance allows a class to inherit methods and attributes from another class.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Hello, my name is {self.name} and I am {self.age} years
old.")
class Employee(Person):
def __init__(self, name, age, position):
super().__init__(name, age)
self.position = position
def work(self):
print(f"{self.name} is working as a {self.position}.")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Employee(Person):
def __init__(self, name, age, position):
super().__init__(name, age) # Initialize Person's attributes
self.position = position
class Person:
def introduce(self):
print("Hello, I am a person.")
class Employee(Person):
def introduce(self): # Overriding the method
print(f"Hello, my name is {self.name} and I work here.")
emp = Employee()
emp.name = "Bob"
emp.introduce() # Overridden method in Employee
class Person:
def introduce(self):
print(f"Hello, I am {self.name}")
class Employee(Person):
def introduce(self):
super().introduce() # Call the parent method
print(f"I work as a {self.position}")
emp = Employee()
emp.name = "David"
emp.position = "Developer"
emp.introduce() # Calls both Person's and Employee's methods
5. Multiple Inheritance
A class can inherit from multiple classes. Here, the `Manager` class inherits from both `Person` and
`Employee`.
class Person:
def introduce(self):
print(f"Hello, I am {self.name}")
class Employee:
def work(self):
print(f"{self.name} is working.")
class Manager(Person, Employee):
def manage(self):
print(f"{self.name} is managing the team.")
mgr = Manager()
mgr.name = "Eve"
mgr.introduce() # Inherited from Person
mgr.work() # Inherited from Employee
mgr.manage() # Defined in Manager