- Constructors in Python
- Python3
- Python3
- Example:
- Python
- Explanation:
- Advantages of using constructors in Python:
- Disadvantages of using constructors in Python:
- Python Class Constructor – Python __init__() Function
- Python __init__() Function Syntax
- Python Class Constructor Examples
- 1. Class with No Constructor
- 2. Simple Constructor with No-Arguments
- 3. Class Constructor with Arguments
- 4. Class Constructor with Inheritance
- 5. Constructor Chaining with Multilevel Inheritance
- 6. Constructor with Multiple Inheritance
- Python Doesn’t Support Multiple Constructors
- Can Python __init__() function return something?
- References:
Constructors in Python
Prerequisites: Object-Oriented Programming in Python, Object-Oriented Programming in Python | Set 2
Constructors are generally used for instantiating an object. The task of constructors is to initialize(assign values) to the data members of the class when an object of the class is created. In Python the __init__() method is called the constructor and is always called when an object is created.
Syntax of constructor declaration :
def __init__(self): # body of the constructor
Types of constructors :
- default constructor: The default constructor is a simple constructor which doesn’t accept any arguments. Its definition has only one argument which is a reference to the instance being constructed.
- parameterized constructor: constructor with parameters is known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer.
Example of default constructor :
Python3
Example of the parameterized constructor :
Python3
print ( «First number line number13 index12 alt2″> print ( «Second number line number14 index13 alt1″> print ( «Addition of two numbers line number15 index14 alt2″>
First number = 1000 Second number = 2000 Addition of two numbers = 3000 First number = 10 Second number = 20 Addition of two numbers = 30
Example:
Python
Default constructor called Method called without a name ('Parameterized constructor called with name', 'John') ('Method called with name', 'John')
Explanation:
In this example, we define a class MyClass with both a default constructor and a parameterized constructor. The default constructor checks whether a parameter has been passed in or not, and prints a message to the console accordingly. The parameterized constructor takes in a single parameter name and sets the name attribute of the object to the value of that parameter.
We also define a method method() that checks whether the object has a name attribute or not, and prints a message to the console accordingly.
We create two objects of the class MyClass using both types of constructors. First, we create an object using the default constructor, which prints the message “Default constructor called” to the console. We then call the method() method on this object, which prints the message “Method called without a name” to the console.
Next, we create an object using the parameterized constructor, passing in the name “John”. The constructor is called automatically, and the message “Parameterized constructor called with name John” is printed to the console. We then call the method() method on this object, which prints the message “Method called with name John” to the console.
Overall, this example shows how both types of constructors can be implemented in a single class in Python.
Advantages of using constructors in Python:
- Initialization of objects: Constructors are used to initialize the objects of a class. They allow you to set default values for attributes or properties, and also allow you to initialize the object with custom data.
- Easy to implement: Constructors are easy to implement in Python, and can be defined using the __init__() method.
- Better readability: Constructors improve the readability of the code by making it clear what values are being initialized and how they are being initialized.
- Encapsulation: Constructors can be used to enforce encapsulation, by ensuring that the object’s attributes are initialized correctly and in a controlled manner.
Disadvantages of using constructors in Python:
- Overloading not supported: Unlike other object-oriented languages, Python does not support method overloading. This means that you cannot have multiple constructors with different parameters in a single class.
- Limited functionality: Constructors in Python are limited in their functionality compared to constructors in other programming languages. For example, Python does not have constructors with access modifiers like public, private or protected.
- Constructors may be unnecessary: In some cases, constructors may not be necessary, as the default values of attributes may be sufficient. In these cases, using a constructor may add unnecessary complexity to the code.
Overall, constructors in Python can be useful for initializing objects and enforcing encapsulation. However, they may not always be necessary and are limited in their functionality compared to constructors in other programming languages.
Python Class Constructor – Python __init__() Function
Python class constructor function job is to initialize the instance of the class. Python __init__() is the constructor function for the classes in Python.
Python __init__() Function Syntax
The __init__() function syntax is:
def __init__(self, [arguments])
- The def keyword is used to define it because it’s a function.
- The first argument refers to the current object. It binds the instance to the init() method. It’s usually named “self” to follow the naming convention. You can read more about it at Python self variable.
- The init() method arguments are optional. We can define a constructor with any number of arguments.
Python Class Constructor Examples
Let’s look at some examples of the constructor function in different scenarios.
1. Class with No Constructor
We can create a class without any constructor definition. In this case, the superclass constructor is called to initialize the instance of the class. The object class is the base of all the classes in Python.
class Data: pass d = Data() print(type(d)) #
Here is another example to confirm that the superclass constructor is called to initialize the instance of the subclass.
class BaseData: def __init__(self, i): print(f'BaseData Constructor with argument ') self.id = i class Data(BaseData): pass d = Data(10) print(type(d))
BaseData Constructor with argument 10
2. Simple Constructor with No-Arguments
We can create a constructor without any arguments. It’s useful for logging purposes such as keeping a count of the instances of the class.
class Data1: count = 0 def __init__(self): print('Data1 Constructor') Data1.count += 1 d1 = Data1() d2 = Data1() print("Data1 Object Count =", Data1.count)
Data1 Constructor Data1 Constructor Data1 Object Count = 2
3. Class Constructor with Arguments
Most of the time, you will find the constructor function with some arguments. These arguments are generally used to initialize the instance variables.
class Data2: def __init__(self, i, n): print('Data2 Constructor') self.id = i self.name = n d2 = Data2(10, 'Secret') print(f'Data ID is and Name is ')
Data2 Constructor Data ID is 10 and Name is Secret
4. Class Constructor with Inheritance
class Person: def __init__(self, n): print('Person Constructor') self.name = n class Employee(Person): def __init__(self, i, n): print('Employee Constructor') super().__init__(n) # same as Person.__init__(self, n) self.id = i emp = Employee(99, 'Pankaj') print(f'Employee ID is and Name is ')
Employee Constructor Person Constructor Employee ID is 99 and Name is Pankaj
- It is our responsibility to call the superclass constructor.
- We can use the super() function to call the superclass constructor function.
- We can also use the superclass name to call its init() method.
5. Constructor Chaining with Multilevel Inheritance
class A: def __init__(self, a): print('A Constructor') self.var_a = a class B(A): def __init__(self, a, b): super().__init__(a) print('B Constructor') self.var_b = b class C(B): def __init__(self, a, b, c): super().__init__(a, b) print('C Constructor') self.var_c = c c_obj = C(1, 2, 3) print(f'c_obj var_a=, var_b=, var_c=')
A Constructor B Constructor C Constructor c_obj var_a=1, var_b=2, var_c=3
6. Constructor with Multiple Inheritance
We can’t use super() to access all the superclasses in case of multiple inheritances. The better approach would be to call the constructor function of the superclasses using their class name.
class A1: def __init__(self, a1): print('A1 Constructor') self.var_a1 = a1 class B1: def __init__(self, b1): print('B1 Constructor') self.var_b1 = b1 class C1(A1, B1): def __init__(self, a1, b1, c1): print('C1 Constructor') A1.__init__(self, a1) B1.__init__(self, b1) self.var_c1 = c1 c_obj = C1(1, 2, 3) print(f'c_obj var_a=, var_b=, var_c=')
C1 Constructor A1 Constructor B1 Constructor c_obj var_a=1, var_b=2, var_c=3
Python Doesn’t Support Multiple Constructors
Python doesn’t support multiple constructors, unlike other popular object-oriented programming languages such as Java.
We can define multiple __init__() methods but the last one will override the earlier definitions.
class D: def __init__(self, x): print(f'Constructor 1 with argument ') # this will overwrite the above constructor definition def __init__(self, x, y): print(f'Constructor 1 with arguments , ') d1 = D(10, 20) # Constructor 1 with arguments 10, 20
Can Python __init__() function return something?
If we try to return a non-None value from the __init__() function, it will raise TypeError.
class Data: def __init__(self, i): self.id = i return True d = Data(10)
TypeError: __init__() should return None, not 'bool'
If we change the return statement to return None then the code will work without any exception.