Python - Inheritance
super()
function in inheritance.
The super()
function in Python is used to call methods and access attributes of the superclass (base class) within a subclass (derived class). It is commonly used in the constructor of the subclass to initialize the attributes inherited from the superclass. This ensures that both the subclass-specific and superclass-specific initialization code is executed.
The syntax for using super()
is typically:
class SubclassName(SuperclassName):
def __init__(self, subclass_params, superclass_params):
super().__init__(superclass_params)
# Subclass-specific initialization code
Let's consider an example to illustrate the purpose of super()
in inheritance:
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
return "Generic animal sound"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def make_sound(self):
return "Woof!"
# Creating an instance of the subclass
dog_instance = Dog("Buddy", "Labrador")
# Accessing attributes and invoking methods
print(dog_instance.name) # Output: Buddy
print(dog_instance.breed) # Output: Labrador
print(dog_instance.make_sound()) # Output: Woof!
In this example, the super().__init__(name)
line inside the constructor of the 'Dog' subclass uses super()
to call the constructor of the 'Animal' superclass. This ensures that the 'name' attribute is properly initialized, allowing the 'Dog' subclass to extend the functionality of the 'Animal' superclass.
The program demonstrates the purpose of super()
in ensuring proper initialization of attributes from the superclass within the subclass, contributing to a more modular and maintainable codebase.
Output:
Buddy Labrador Woof!
In Python, inheritance allows a class to inherit attributes and methods from one or more classes. The two main types of inheritance are single inheritance and multiple inheritance.
Single Inheritance: In single inheritance, a class can inherit from only one superclass. The syntax for defining a class with single inheritance is straightforward.
class BaseClass:
def method(self):
return "Method from BaseClass"
class DerivedClass(BaseClass):
def derived_method(self):
return "Method from DerivedClass"
Multiple Inheritance: In multiple inheritance, a class can inherit from more than one superclass. This allows the subclass to access and combine the attributes and methods of multiple classes. The syntax involves specifying multiple superclasses separated by commas.
class FirstClass:
def method(self):
return "Method from FirstClass"
class SecondClass:
def method(self):
return "Method from SecondClass"
class MultipleDerivedClass(FirstClass, SecondClass):
def derived_method(self):
return "Method from MultipleDerivedClass"
Let's consider an example to illustrate the difference between single and multiple inheritance:
# Single Inheritance Example
class Animal:
def speak(self):
return "Generic animal sound"
class Dog(Animal):
def bark(self):
return "Woof!"
# Multiple Inheritance Example
class Bird:
def chirp(self):
return "Chirp"
class Parrot(Animal, Bird):
def fly(self):
return "Parrot flying"
In the single inheritance example, the 'Dog' class inherits from the 'Animal' class. In the multiple inheritance example, the 'Parrot' class inherits from both the 'Animal' and 'Bird' classes.
The program demonstrates creating instances of the classes and invoking methods to showcase the difference between single and multiple inheritance.
Output:
# Single Inheritance Outputs dog_instance = Dog() print(dog_instance.speak()) # Output: Generic animal sound print(dog_instance.bark()) # Output: Woof! # Multiple Inheritance Outputs parrot_instance = Parrot() print(parrot_instance.speak()) # Output: Generic animal sound print(parrot_instance.chirp()) # Output: Chirp print(parrot_instance.fly()) # Output: Parrot flying
isinstance()
and issubclass()
functions in Python.
In Python, the isinstance()
and issubclass()
functions are built-in functions that help check relationships between objects and classes.
isinstance()
: This function is used to check if an object is an instance of a specified class or a tuple of classes. It returns True
if the object is an instance of any of the specified classes, and False
otherwise.
# isinstance() Example
class Animal:
pass
class Dog(Animal):
pass
dog_instance = Dog()
print(isinstance(dog_instance, Dog)) # Output: True
print(isinstance(dog_instance, Animal)) # Output: True
print(isinstance(dog_instance, str)) # Output: False
In the example above, isinstance()
is used to check if dog_instance
is an instance of the 'Dog' and 'Animal' classes. It returns True
for both checks.
issubclass()
: This function is used to check if a class is a subclass of a specified class or a tuple of classes. It returns True
if the class is a subclass of any of the specified classes, and False
otherwise.
# issubclass() Example
class Animal:
pass
class Dog(Animal):
pass
print(issubclass(Dog, Animal)) # Output: True
print(issubclass(Animal, Dog)) # Output: False
print(issubclass(Dog, object)) # Output: True
In the example above, issubclass()
is used to check if 'Dog' is a subclass of 'Animal'. It returns True
. It also checks if 'Animal' is a subclass of 'Dog', which returns False
. Finally, it checks if 'Dog' is a subclass of the base class 'object', which returns True
.
The program demonstrates the use of isinstance()
and issubclass()
to check relationships between instances and classes.
Output:
# isinstance() Outputs True True False # issubclass() Outputs True False True
In Python, method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. This allows the subclass to customize or extend the behavior of the inherited method. Method overriding is achieved by defining a method with the same name in the subclass as the one in the superclass.
Let's consider an example to illustrate method overriding in Python:
class Animal:
def make_sound(self):
return "Generic animal sound"
class Dog(Animal):
def make_sound(self):
return "Woof!"
# Creating instances of the superclass and subclass
animal_instance = Animal()
dog_instance = Dog()
# Invoking the overridden method
print(animal_instance.make_sound()) # Output: Generic animal sound
print(dog_instance.make_sound()) # Output: Woof!
In this example, the 'Animal' class has a method 'make_sound', and the 'Dog' class, which is a subclass of 'Animal', overrides this method with its own implementation. When you create instances of both classes and invoke the 'make_sound' method, you get the customized output based on the class type.
The program demonstrates how method overriding allows a subclass to provide a specific implementation for a method inherited from its superclass, promoting flexibility and customization.
Output:
Generic animal sound Woof!