Constructor in Python

post

In Python, a constructor initializes instance members of a class and is the first method executed when an object is created.

What is a Constructor in Python?

In object-oriented programming, a Python constructor is a special method used to initialize the instance members of a class. It ensures that when an object of the class is created, the constructor is the first to execute.

Without a constructor, you can initialize a class attribute as follows:

class Three:    val = 7 

Alternatively, you can define methods to set or re-initialize attributes within the class.

class Three:    def func(self, val):        self.val = val t = Three() t.func(8) print(t.val)

You can also prompt the user for input.

class Three:    def __init__(self):        self.val = input("What value?")         t = Three() print(t.val)

Declaring a Python Constructor

1. Object Creation

The __new__ method is a static class method used to control object creation. Every time a constructor is called, it invokes __new__. We can customize this behavior:

class Demo:    def __new__(self):        return 'Debugshala' d = Demo() print(type(d))  # <class 'str'> 

2. Object Initialization

In Python, the constructor is defined as __init__(), and it is used to initialize an object:

class Citrus:    def __init__(self):        self.detoxifying = True            def show(self):        if self.detoxifying:            print("I detoxify")        else:            print("I do not detoxify") kumquat = Citrus() kumquat.show()  # Output: I detoxify 

Here, __init__() is used to initialize attributes like detoxifying.

3. Adding New Attributes

You can add new attributes for an object after initialization:

kumquat.color = 'orange' print("I am", kumquat.color)  # Output: I am orange 

4. No Constructor in a Class

If you don't define a constructor, Python automatically provides a default constructor:

class Color:    def show(self):        print("You can see me") orange = Color() orange.show()  # Output: You can see me 

Types of Python Constructors

Default Constructor
This constructor does nothing but instantiate an object. Python provides this when no constructor is defined:

Non-Parameterized Constructor
This constructor does not take any parameters except self and can be used for tasks like setting default values:

Parameterized Constructor
This constructor allows you to pass arguments when creating an object:

No Constructor Overloading in Python

Python does not support constructor overloading. If you define multiple __init__() methods, the last one will override the previous ones:

class One:    def __init__(self):        print("First constructor")    def __init__(self, val):        self.val = val        print("Second constructor", val) o = One(2)  # Output: Second constructor 2 

Even if you try default arguments, it’s just using default values, not overloading:

class One:    def __init__(self, a=1, b=2):        print(a + b) o = One(2)  # Output: 4 o1 = One(2, 3)  # Output: 5 o2 = One()  # Output: 3 

Conclusion

We’ve explored parameterized and non-parameterized constructors, default constructors, and object creation and initialization in Python. We also learned that Python does not support constructor overloading, and default arguments can mimic this behavior.

class Demo:    def __init__(self, age, country):        self.age = age        self.place = country    def hello(self):        print(f"Hello, I am a {self.age}yo from {self.place}") d = Demo(22, 'Romania') d.hello()  # Output: Hello, I am a 22yo from Romania 

class Demo:    def __init__(self):        print("Thank you for instantiating me :)") d = Demo()  # Output: Thank you for instantiating me 🙂 

class Demo:    def show(self):        print("Thank you for instantiating me :)") d = Demo() d.show()  # Output: Thank you for instantiating me 🙂 


Share This Job:

Write A Comment

    No Comments