Multiple Constructors in Python
You must know about python constructors and how to initialize in the class.
What is Constructors in Python?
A constructor is a special kind of method (function) that is used to initialize the instance of the class. Python considers the constructors differently but the C++ and Java declare the same name as the class.
There are two types of constructors:
- Parameterized Constructor
- Non-parameterized Constructor
To create a constructor in python, we will use the __init__() function. When the class is created, this method is invoked. It takes the self keyword as a first parameter, allowing access to the class’s properties and methods.
Create Multiple Constructors in Python Class
You can create multiple constructors in class and you can customize it according to the parameters. Constructors will be run based on the different number of parameters.
Let’s create multiple Constructors with constructor overloading.
- class Result:
- def __init__(self, *args):
- if len(args) > 1:
- self.answer = 0
- for i in args:
- self.answer += i
- elif isinstance(args[0], int):
- self.answer = args[0]*args[0]
- elif isinstance(args[0], str):
- self.answer = "Hope you understand the "+args[0]+"."
- a1 = Result(1, 2, 13, 6, 8, 5, 9)
- a2 = Result(8)
- a3 = Result("Multiple Constructors")
- print("Square of integer:", a2.answer)
- print("Sum of list:", a1.answer)
- print(a3.answer)
Output:
Square of integer: 64Sum of list: 44
Comments
Post a Comment