Object Oriented Programming/Constructors
What is a constructor?
editIn Object Oriented Programming, a constructor is a function that is executed when a new class object is created. This subroutine ensures that the class is properly instantiated. The constructor first checks to make sure that there are enough resources(memory) available to create the new object and then allocates the memory. Afterwards, the constructor can execute the custom code that can be optionally provided by the programmer. This is useful if each class has passed in data when created, making each class unique. You can use the constructor to assign the passed in parameters to specific properties within the class, while possibly calling other class methods for data manipulation within the constructor if needed. It's important to note that constructors are only called once per object, so once a class has been instantiated, the constructor will not be used again for that particular instance of the class.
Example
edit- Class.py
class Values():
def __init__(self, value):
self.value = squared(value)
def squared(self, value):
self.value = self.value * self.value
- Main.py
from Class.py import Values
instance = Values(4)
print(instance.value())
# Output: 16
From the example above, you can see that we have an __init__ function. In Python, this is the programmer controlled aspect of the class constructor. This example shows that the constructor takes the passed in value, and squares it. This is all done when the class is instantiated with no methods being directly called by Main.py. Constructors are very handy in situations when there are passed-in values, when the class is instantiated, as well as when those passed in values have to be manipulated before use.