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:

  1.  Parameterized Constructor
  2. 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.

  1. class Result:  
  2.  
  3. def __init__(self, *args):  
  4.  
  5. if len(args) > 1:  
  6. self.answer = 0 
  7. for i in args:  
  8. self.answer += i  
  9.  
  10. elif isinstance(args[0], int):  
  11. self.answer = args[0]*args[0]  
  12.  
  13. elif isinstance(args[0], str):  
  14. self.answer = "Hope you understand the "+args[0]+"." 
  15.  
  16.  
  17. a1 = Result(1, 2, 13, 6, 8, 5, 9)  
  18. a2 = Result(8)  
  19. a3 = Result("Multiple Constructors")  
  20.  
  21. print("Square of integer:", a2.answer)  
  22. print("Sum of list:", a1.answer)  
  23. print(a3.answer) 
  24.  

Output:

Square of integer: 64

Sum of list: 44

 
  

Comments

Popular posts from this blog

What is the Difference Between Git fetch and Git pull?

WooCommerce Redirect to Checkout After Click on Add to Cart

Multiple Where Condition in Laravel Eloquent