Inheritance allows us to define a class that inherits all the methods and properties from another class. Here’s a detailed example:
# Base class or Parent class
class Person:
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
def printFullName(self):
print(self.firstName + ' ' + self.lastName)
# Derived class or Child class
class Student(Person):
def __init__(self, firstName, lastName, studentID):
super().__init__(firstName, lastName) # Calling the constructor of the Parent class
self.studentID = studentID
def printStudentID(self):
print(f"Student ID: {self.studentID}")
# Creating an object of the Base class
personObj = Person("John", "Doe")
personObj.printFullName() # Output: John Doe
# Creating an object of the Derived class
studentObj = Student("Jane", "Doe", "S12345")
studentObj.printFullName() # Output: Jane Doe
studentObj.printStudentID() # Output: Student ID: S12345
In this example:
- The
Person
class is the base class with a constructor that initializesfirstName
andlastName
. - The
Student
class is the derived class that inherits fromPerson
. It has its own constructor that initializesstudentID
and calls the base class constructor usingsuper()
to initializefirstName
andlastName
. - Both classes have their own methods, and the derived class can also access the methods and properties of the base class.
Multiple Inheritance
In Python, a class can inherit from more than one base class.
# Base class 1
class Person:
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
def printFullName(self):
print(self.firstName + ' ' + self.lastName)
# Base class 2
class Employee:
def __init__(self, employeeID):
self.employeeID = employeeID
def printEmployeeID(self):
print(f"Employee ID: {self.employeeID}")
# Derived class inheriting from both Person and Employee
class Manager(Person, Employee):
def __init__(self, firstName, lastName, employeeID, department):
Person.__init__(self, firstName, lastName)
Employee.__init__(self, employeeID)
self.department = department
def printDetails(self):
self.printFullName()
self.printEmployeeID()
print(f"Department: {self.department}")
# Creating an object of the derived class
managerObj = Manager("Alice", "Smith", "E6789", "Sales")
managerObj.printDetails()
# Output:
# Alice Smith
# Employee ID: E6789
# Department: Sales
Method Overriding
A derived class can override a method from the base class.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
# Creating objects of both classes
animalObj = Animal()
dogObj = Dog()
animalObj.speak() # Output: Animal speaks
dogObj.speak() # Output: Dog barks
Using super()
to call the parent class methods
You can use super()
to call the parent class methods and constructors.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Cat(Animal):
def __init__(self, name, age):
super().__init__(name) # Call the constructor of the Animal class
self.age = age
def speak(self):
super().speak() # Call the speak method of the Animal class
print(f"{self.name} meows and is {self.age} years old")
# Creating an object of the derived class
catObj = Cat("Whiskers", 3)
catObj.speak()
# Output:
# Whiskers makes a sound
# Whiskers meows and is 3 years old
Class Variables and Instance Variables
Class variables are shared across all instances of the class, whereas instance variables are unique to each instance.
class Car:
wheels = 4 # Class variable
def __init__(self, color, model):
self.color = color # Instance variable
self.model = model # Instance variable
# Creating objects of the Car class
car1 = Car("Red", "Sedan")
car2 = Car("Blue", "SUV")
print(f"Car1: {car1.color}, {car1.model}, Wheels: {car1.wheels}")
print(f"Car2: {car2.color}, {car2.model}, Wheels: {car2.wheels}")
# Output:
# Car1: Red, Sedan, Wheels: 4
# Car2: Blue, SUV, Wheels: 4
# Modifying class variable
Car.wheels = 5
print(f"Car1: {car1.color}, {car1.model}, Wheels: {car1.wheels}")
print(f"Car2: {car2.color}, {car2.model}, Wheels: {car2.wheels}")
# Output:
# Car1: Red, Sedan, Wheels: 5
# Car2: Blue, SUV, Wheels: 5
Class Methods and Static Methods
Class methods and static methods can be defined using @classmethod
and @staticmethod
decorators.
class MathOperations:
@staticmethod
def add(x, y):
return x + y
@classmethod
def multiply(cls, x, y):
return x * y
# Using static method
print(MathOperations.add(5, 3)) # Output: 8
# Using class method
print(MathOperations.multiply(5, 3)) # Output: 15
Example: Class and Object Usage with Advanced Concepts
Inheritance with Method Overriding and Use of super()
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def full_name(self):
return f"{self.first_name} {self.last_name}"
class Student(Person):
def __init__(self, first_name, last_name, student_id):
super().__init__(first_name, last_name)
self.student_id = student_id
def full_name(self):
return f"{self.first_name} {self.last_name}, ID: {self.student_id}"
person = Person("John", "Doe")
student = Student("Jane", "Doe", "12345")
print(person.full_name()) # Output: John Doe
print(student.full_name()) # Output: Jane Doe, ID: 12345
Class and Instance Variables
class Car:
# Class variable
num_wheels = 4
def __init__(self, make, model):
# Instance variables
self.make = make
self.model = model
# Create instances of Car
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Civic")
print(car1.num_wheels) # Output: 4
print(car2.num_wheels) # Output: 4
# Modify class variable
Car.num_wheels = 3
print(car1.num_wheels) # Output: 3
print(car2.num_wheels) # Output: 3
Class Methods and Static Methods
class MathOperations:
@staticmethod
def add(a, b):
return a + b
@classmethod
def subtract(cls, a, b):
return a - b
# Using the static method
result = MathOperations.add(5, 3)
print(result) # Output: 8
# Using the class method
result = MathOperations.subtract(10, 4)
print(result) # Output: 6