In Python, every class has a constructor, which is a special method specified inside the class. The constructor/initializer will be called automatically when a new object is created for the class. When an object is initialized, the constructor assigns values to data members in the class.
There is no need to explicitly define the constructor. But in order to create a constructor we need to follow the following rules -
For a class, it only allows one constructor.
The constructor name must be __init__.
Constructors must be defined using instance properties (just specify the self keyword as the first argument).
It cannot return any value except None.
class A(): def __init__(self): pass
Consider the following example and understand how constructors work.
class SampleClass(): def __init__(self): print("it a sample class constructor") # creating an object of the class A = SampleClass()
it a sample class constructor
In the above block, object A is created for SampleClass(), and for this instance, the method __init__(self) is automatically executed. This way it shows the constructor statement.
Constructors are divided into three types.
Default constructor
Parameterized constructor
Non-parametric constructor
The default constructor is not defined by the user, Python itself creates a constructor during program compilation. It does not perform any tasks but initializes the object.
Python generates an empty constructor with no code in it. See 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()
1000
Let us use Python’s built-in dir() function to verify the constructor of class A.
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']
python dir() The function returns a list of all properties and methods of the specified object. In the above list we can see that the default constructor __init__ is created for object A.
The parameterized constructor accepts one or more parameters and self. It is useful when you want to create an object with custom property values. Parameterized constructors allow us to specify the values of object properties when creating an object.
Let’s look at 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()
Number of members is 25
Here the object Joy series is created using a custom value of 25 instead of using the default member property value of 10. And the value is available to this instance because it is assigned to the self.members property.
Non-parameterized constructors do not accept any parameters except self. It is useful when you want to manipulate the value of an instance property.
Let’s look at an example of a non-parametric constructor.
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()
player1 results 2 2 p2 results 0
player1 object operates the "position" property by using the move() method. And the p2 object accesses the default value of the "position" property.
The above is the detailed content of Constructor in Python. For more information, please follow other related articles on the PHP Chinese website!