Every object-oriented programming language supports the concept of class and objects to implement the properties of Object Orientation programming. And as an object-oriented programming language, Python also supports classes and objects.
Using the class syntax, we can follow or use the properties of OOPs, such as Data Abstraction, Inheritance, Data Encapsulation, and Polymorphism. And when we specifically talk about class and object, one of the main topics that every programmer learns or needs to know is Constructor.
All the programming languages that follow the object-oriented programming principle support the concept of Constructor, whether you talk about C++, Java, or Python. However, the declaration of constructors in Java and C++ is different from Python, but the overall concept is the same. Before we get started with the Python constructor, you must know what classes and objects in Python are.
What are classes in Python?
A class is nothing but a blueprint for a structure or object. What does it mean? If we define a class in layman's terms, we can say that a class is like a frame for some object that only defines some rules. It's like having a plan written on plain paper that defines some functions (methods) and values (attributes).
With the help of the class, we can easily define many things using programming. For example, we can define a blueprint for a man, car, bus, animal, etc., and follow along. We can define their function and values.
Syntax
class class_name: ....
Example
class Car: name = "Toyota" def run(self): print(f"{self.name} is running")
Now we have a
class
called Car, with
name,
attribute, and
run()
method. The variables or values defined inside a class are known as class attributes, and the functions are known as class methods. Even after defining a class, it will bring no action to the program and memory until or unless because, as said, it is just a blueprint with no existence. To use the Rahul class and its values, we need to define its object.
Theself
parameter represent the object, and it is mendetory that every method should haveself
as a first parameter.
What are objects in Python?
An object is an instance of a class, and a class can have more than one object. The object is the real deal; it is a thing that is capable of performing tasks. We can say that a class is a car's blueprint and an instance is an actual car with a solid body and all the features that a customer buys.
To create an object of a class, we use the following syntax:
Syntax
obj_name = Class_Name()
Example
Let's use the above Car class and create its object.
class Car: name = "Toyota" def run(self): print(f"{self.name} is running") # create object rahul_car = Car() # access car name property print("Car Name: ", rahul_car.name) # access car run methods rahul_car.run()
Output
Car Name: Toyota Toyota is running
What is a constructor (__init__) in Python?
A constructor is a special method defined in the class that gets automatically called when we initialize or define the class object. Generally, to call a class method, we use the class object followed by the dot operator and method name, but the constructor class gets automatically invoked during the object initialization. The python constructor method has a special syntax, and it is one of the dunder methods.
Syntax
def __init__(self): ......
Example
class Demo: # constructor def __init__(self): print("I am inside the constructor method") def method1(self): print("I am inside the method1") def method2(self): print("I am inside the method2") # initialize the Demo object obj = Demo()
Output
I am inside the constructor method
Break the code
In the above example, we have defined a class by name
Demo
and it has 3 methods
__init__(self)
,
method1(self)
and
method(2)
, but when we initialize its object
obj = Demo()
it automatically calls the
__init__()
method.
This is because
__init__()
defines the constructor method for the Demo() class, and as the feature state, the constructor method gets automatically executed when the class object is created. For the rest of the normal methods, we can call those using the object name followed by the dot operator and method name.
Why use a constructor in Python?
As the constructor method gets automatically invoked when a new class object is created, we use this feature of class for the early initialization of class attributes. The whole idea of defining a constructor method is so we can initialize initial values to the class attributes when the object gets created.
Like the normal method, the constructor method can also accept arguments, so when we define or initialize a class object, we can pass argument values along with the class name, and it will go to the
__init__(self)
constructor method.
Example
class CarDetail: # constructor def __init__(self, owner, car_name, number_plate): # attributes self.owner = owner self.car_name = car_name self.number_plate = number_plate # method def register_detail(self): print(f"This {self.car_name} with [{self.number_plate}] belongs to {self.owner}") # initilize the first object rahul_car = CarDetail("Rahul", "Toyota Grand", "DL-FG-45E") # initilize the second object rohan_car = CarDetail("Rohan", "Honda City", "DL-FF-45H") # access rahul car details rahul_car.register_detail() # access rohan car details rohan_car.register_detail()
Output
This Toyota Grand with [DL-FG-45E] belongs to Rahul This Honda City with [DL-FF-45H] belongs to Rohan
Behind the code
For both the objects
rahul_car
and
rohan_car
we have the same class, but during their object initialization, we pass different values to the
__init__(self)
method. For
rahul_car
object we pass
("Rahul", "Toyota Grand", "DL-FG-45E")
parameter values and for
rohan_car
we pass the
("Rohan", "Honda City", "DL-FF-45H")
values. And when we did that the
__init__(self)
, called for both the object and initialized the values difference values for them.
Conclusion
Constructor is one of the major properties of class and objects. A constructor is a special method that automatically gets called for an object when the object is created. Generally, the constructor is used to initialize some values for the object when the object gets created. It is not mandatory to define a constructor method for every class, it is a feature that has its usages, and we can define and use our class and object without even defining the constructor method.
People are also reading:
- Null in Python
- Python typeerror: ‘str’ object is not callable Solution
- How to install Python 3 on Windows 10?
- Python TypeError: ‘float’ object cannot be interpreted as an integer Solution
- How to Install PIP on Windows, macOS, and Linux?
- Python TypeError: ‘method’ object is not subscriptable Solution
- Python vs Scala
- Python TypeError: ‘NoneType’ object is not callable Solution
- R vs Python
- Python ValueError: invalid literal for int() with base 10: Solution
Leave a Comment on this Post