Default Constructor

Default Constructor

- Default Constructor runs with parameters and without parameters.

- Below classes are examples of default constructors.


Not Declare a Constructor:

Explanation of the Below Code:

- We access the class variable without an init method(constructor).

- We create a 
chirag-named class.

- We create a lastname-named class variable.

- Then we define a readlastname-named method with a self-parameter
we take the class variable in the print function which returns the value of class variable.

- Then we create an a-named instance(object) of the chirag class and then we call the readlastname method using a-named instance(object).


Declare a Constructor:

Explanation of the Below Code:

- We create a class with the init method.

- We create a 
chirag-named class.

- We create an age-named class variable.

- Then we define the init method with self-parameters, then create an instance variable.

- Then we define a readAge-named method with a self-parameter, we take the instance variable in the print function which returns the instance variable value.

- Then we create an a-named instance(object) of the chirag class.

- Then we call the readAge method using the a-named instance(object).


Syntax: def __init__(self):


Constructor without parameters:

Explanation of the Below Code:

- We create a class with the init method.

- We create a chirag
-named class.

- Then we define the init method with self-parameters, then print one string.

- Then we define a showfullname-named method with the self and fullname parameters, we take the fullname parameter in the print function which returns the value of fullname inside the given string (separate with a comma).

- Then we create an a-named instance(object) of the chirag class.

- Then we call the showfullname method using the a-named instance(object) with one argument. (showfullname method parameter(fullname) requires its own argument("chirag chauhan"))


Comments