Python Constructors: A Comprehensive Guide for Effective Programming

Unlock the full potential of Python constructors with our comprehensive guide. Elevate your programming skills for effective and efficient code development.

In Python every class has a constructor, it is a special method specified inside a class. The constructor/initializer will automatically invoke while creating a new object for the class. When an object is initialized, the constructor assigns values to the data members within the class.

It is not necessary to define a constructor explicitly. But for creating a constructor we need to follow the below rules:

  • For a class, it allows only one constructor.
  • The constructor name must be __init__.
  • A constructor must be defined with an instance attribute (nothing but specifying the self keyword as a first parameter).
  • It cannot return any value, except None.

Syntax

class A(): 
   def __init__(self):
      pass

Example

Consider the below example and understand the working of a constructor.

class SampleClass():
  def __init__(self):
    print("it a sample class constructor")

# creating an object of the class 
A = SampleClass()

Output

it a sample class constructor

In the above block, object A is created for the SampleClass() and for this instance, the method __init__(self) is automatically executed. So that it has displayed the statement from the contructor.

Constructors are three types:

  • Default constructor
  • Parameterized Constructor
  • Non-Parameterized Constructor

Default Constructor

Default constructors are not defined by the user, Python itself creates a constructor during the compilation of the program. It doesn’t perform any task but initializes the objects.

Example

Python generates an empty constructor that has no code in it. See the example below.

class A():
    check_value = 1000
    # a method
    def value(self):
        print(self.check_value)

# creating an object of the class
obj = A()

# calling the instance method using the object
obj.value()

Output

1000

Let’s verify the constructor of the class A using the python built in dir() function.

dir(A)
Output:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', 
'__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__', '__weakref__', 'check_value', 'value']

The python dir() function returns a list of all properties and methods of the specified object. In the above list we can see that default constructor __init__ is created for the object A.

Parameterized Constructor

The parameterized constructor, takes one or more arguments along with self. It is useful when you want to create an object with custom values for its attributes. The parameterized constructor allows us to specify the values of the object’s attributes when the object is created.

Example

Let’s see an example of a class with a parameterized constructor

class Family:
   members = 10
   def __init__(self, count):
      self.members = count
   
   def disply(self):
      print("Number of members is", self.members)  

joy_family = Family(25)
joy_family.disply()

Output

Number of members is 25

Rather than using the default members attribute value 10, here the object joy family is created with the custom value 25. And this value can be utilized for this instance as it is assigned to the self.members attribute.

Non-Parameterized Constructor

The non-parameterized constructors don’t take any arguments other than self. It is useful when you want to manipulate the values of the instance attributes.

Example

Let’s see an example for non-parameterized constructors.

class Player:
   def __init__(self):
      self.position = 0
   
   # Add a move() method with steps parameter     
   def move(self, steps):
      self.position = steps
      print(self.position)
   
   def result(self):
      print(self.position)

player1 = Player()
print('player1 results')
player1.move(2)
player1.result()

print('p2 results')
p2 = Player()
p2.result()

Output

player1 results
2
2
p2 results
0

The player1 object is manipulated the “position” attribute by using the move() method. And the p2 object is accessed the default value of the “position” attribute.

#python

Python Constructors: A Comprehensive Guide for Effective Programming
12.40 GEEK