In this Python oops program, we will create multiple classes in Python and access them using a single class. This example illustrates a way to handle objects of different classes using type-checking and conditional statements.
Create multiple classes in Python
Steps to solve the program
- Five classes (Class1, Class2, Class3, Class4, and Class5) are defined, each with a single method that prints a specific message.
- A list named classes is created, which contains instances of the five defined classes.
- A loop iterates over each object (obj) in the classes list.
Inside the loop, conditional statements (if, elif) are used to check the type of the object using the isinstance() function. Depending on the object’s class, the corresponding method is called using dot notation. - For example, if the object is an instance of Class1, the method1() of Class1 is called.
- This pattern repeats for each class, ensuring that the appropriate method is called for each object.
Output:
Related Articles
Create 5 Python classes and set up multilevel inheritance among all the classes.
Set Instance variable data with setattr and getattr methods.
Python oops program with encapsulation.
Create a Python class called Rectangle with attributes length and width.
Create a Python class called Circle with attributes radius.
Create a Python class called Person with attributes name and age.