Python Constructors
A constructor is a special type of method (function) which is used to initialize the instance members of the class. The constructor can be parameterized and non-parameterized as well. Constructor definition executes when we create an object of the class. Constructors also verify that there are enough resources for the object to perform any start-up task.
Creating a Constructor
A constructor is a class function that begins with a double underscore (_). The name of the constructor is always the same __init__().
While creating an object, a constructor can accept arguments if necessary. When we create a class without a constructor, Python automatically creates a default constructor that doesn't do anything.
Every class must have a constructor, even if it simply relies on the default constructor.
Python Constructor Example
Let's create a class named ComplexNumber, having two functions __init__() function to initialize the variable and getData() to display the number properly.
0 comments:
Post a Comment