Python Class Constructor - codebugfree


python class constructor

Python constructor is the method or function. Which is used to pass attributes to the object. In other programming language like c and c++ their is a same name as constructor class but in python constructor treats or use differently in python.

Types of Python Class Constructor

There are mainly two types of python class constructor they are
1) Non parameterized python class constructor
2) parameterized python class constructor

Non Parameterized python class constructor

Non parameterized have also two types of constructor they are:
1) Declare python constructor
2) Without Declare python constructor

Example of Declare python constructor

#creating the object
class python_class_constructor:
    # it is python class constructor
    def __init__(self):
        self.best_number = 7

    def print_best_number(self):
        print(f"The best number is {self.best_number}")
#creating the object
today_class = python_class_constructor()

Here first we create a class constructor. Declare a python class constructor. Make a variable as self.best_number. Print the variable using another def function. create the object as today class. 


The best number is 7

Example without Declare constructors

class python_constructors():
    my_number = 17
    print(f"My number is {my_number}")
today_section = python_constructors()

It is simple than Declare constructors but this constructor has less chance to use this constructor.


My number is 17

Parameterized python class constructor

Parametrized python class constructor is passing the attributes or variable to object. It is most use in oops.

Example of parametrized constructor  

#creating class 
class class_constructor():
    # python class constructors
    def __init__(self,favroite_number):
        self.favroite_number = favroite_number
    def print_favroite_number(self):
        print(f"my favroite number is {self.favroite_number}")
    # creating a object and pass attributes
today_python_class = class_constructor(77)

First creating a class constructor. Making init python constructor passing the attribute to object favorite number. Another def function is trying to print favroite number. creating the object.

Post a Comment