Introduction to init in Python
Within Python’s object-oriented programming paradigm, the method init in Python, often called a constructor, occupies a critical position in object initialization. This special method is invoked automatically upon instantiating a new object from a defined class. Its primary function is assigning values to an object’s attributes, defining its initial state, which defines its characteristics and behavior. Notably, __init__ executes behind the scenes, eliminating the need for explicit calls. The true power of __init__ lies in its ability to accommodate custom logic. It enables developers to perform essential setup tasks for their objects, such as input validation, calculations, or establishing external resource connections. By leveraging __init__ effectively, you can construct well-structured and reusable classes, guaranteeing that your objects commence their existence in a well-defined and operational state.
Note that The init method, also known as a magic function, initializes an object upon creation. Python automatically calls magic functions whenever certain actions occur on an object. There are other magic functions too, like __init__, __add__, __len__, __str__, etc. Magic methods can overload operators and implement custom behavior for objects. These are dunder methods because they start and end with two underscores.
Table of Contents
Syntax and Parameters
Syntax:
class ClassName:
def __init__(self, parameter1, parameter2, ...):
# Initialization code
self.parameter1 = parameter1
self.parameter2 = parameter2
...
Parameters:
- The first parameter of the __init__ method represents the object. This parameter is always called self. The “self” is a reference parameter to the instance. We have assigned the passed values to the function body.
- You can optionally assign values to the object’s attributes using different parameters.
Key takeaways
- The special method is called a constructor. It automatically runs when you create a new object from a class.
- It is also known as the constructor method because it works like the constructor used in C++.
- You can identify magic (or dunder) functions by their double underscores (e.g., __init__). These functions execute automatically when you perform specific actions on an object.
- The __init__ method allows you to initialize an object’s attributes (variables).
- It takes the object as its first argument. Other arguments are optional.
- The __init__ method does not return any value.
Why use__init__ in Python?
- Sets up the initial state: The primary purpose of __init__ is to establish an object’s foundation upon its creation. It involves defining and initializing the object’s attributes (its data).
- Assigning values: When you assign values within __init__, you ensure that a newly created object starts with the necessary data, making it usable and avoiding potential errors.
- Setup tasks: __init__ is the perfect place to handle any setup processes crucial for the object to function correctly. These processes include establishing database connections, opening files, and any preparatory steps.
- Customization: Parameters passed to __init__ allow you to create objects with varying initial states, making your classes more flexible and adaptable to different use cases.
- Encapsulation: Encapsulation, a core principle of object-oriented programming, is promoted by keeping initialization logic within the class definition. It helps maintain code clarity and avoids external dependencies affecting the object’s internal state.
- Correctly configured objects: __init__ guarantees that objects are created in a valid and usable state, promoting code reliability and reducing the risk of unexpected errors.
How does the init() method work?
Since the __init__ method is defined within the class, when you create an object of that class, you can assign values to its attributes directly (whenever you make it) or use this __init__ method to initialize them. This method earns its name “automatic” due to its magical function. It assigns attributes to those passed values.
Using the __init__ Method
1. Basic Example
Code:
# Class
class EduTech:
def __init__(self, courseName, platformName): # __init__ function
self.course = courseName
self.platform = platformName
# Instance of EduTech class
eduCBA = EduTech("Python Programming", "EDUCBA")
print("This course is", eduCBA.course, "offered on the", eduCBA.platform, "platform.")
Output:
Explanation:
- Class Definition:
- There is an EduTech class defined.
- It has an __init__ method to initialize attributes course and platform.
- The init method takes the parameters courseName and platformName.
- course and self.platform are assigned the values of courseName and platformName, respectively.
- Instance Creation and Output:
- We have created an instance eduCBA of the EduTech class.
- We have passed arguments “Python Programming” and “eduCBA” to initialize the instance.
- We used dot notation (eduCBA.course and eduCBA.platform) for course and platform attributes that are accessed and printed.
- Note:
- We have accessed instances (eduCBA.course and eduCBA.platform) using dot notation.
- You can also put the print statement inside the __init__ method.
2. Multiple Arguments
The __init__ method can have multiple arguments to initialize object attributes. You can put multiple parameters separated by commas. For example, we already have more than one argument on the above __init__ method. These are courseName and platformName. You can also add more. For example, if we add instructorName as another parameter of the above init method, it will accept three parameters:
# Class
class EduTech:
def __init__(self, courseName, platformName, instructorName):
self.course = courseName
self.platform = platformName
self.instructor = instructorName
# Instance creation
course = "Python Programming"
platform = "eduCBA"
instructor = "Phill Flintoff"
eduCBA = EduTech(course, platform, instructor)
# Printing instance values
print("Course:", eduCBA.course)
print("Platform:", eduCBA.platform)
print("Instructor:", eduCBA.instructor)
Output:
Explanation:
- Class Definition:
- There is an EduTech class defined.
- It has an __init__ method to initialize course, platform, and instructor attributes.
- We have passed parameters courseName, platformName, and instructorName to the __init__ method.
- The self.course, self.platform, and self.instructor are assigned the values of courseName, platformName, and instructorName, respectively.
- Instance Creation and Output:
- The values “Python Programming,” “eduCBA,” and “Phill Flintoff” are assigned to the course, platform, and instructor, respectively.
- We have created an instance named eduCBA of the EduTech class.
- We have passed the arguments course, platform, and instructor to initialize the instance.
- Access and print the instance’s course, platform, and instructor attributes using dot notation (eduCBA.course, eduCBA.platform, and eduCBA.instructor).
- Note:
- You can print statements using the __init__ method.
3. Default Values
You can have default parameter values in the __init__ method if you do not want to pass the exact value of a parameter. Then, you can set its value to default. For example, we will put the default value “eduCBA” of the plateformName. So you do not need to pass each time whenever you create an instance.
Output:
Explanation:
- Class Definition:
- There is an EduTech class defined.
- It has an __init__ method to initialize attributes of course and platform.
- We have passed parameters courseName and platformName to the __init__ method. Note that platformName has “EDUCBA” as the default value.
- The self.course and self.platform are assigned the values of courseName and platformName, respectively.
- Instance Creation and Output:
- We have created an instance named EDUCBA of the EduTech class.
- We have passed arguments “Python Programming” to initialize the instance. Note that no value is passed for platformName.
- We used dot notation (eduCBA.course and eduCBA.platform) for course and platform attributes accessed and printed.
- Note:
- If you do not pass the value of platformName, then the init method will assign its default value, i.e., EDUCBA. The init method will assign this value to its first-course variable. If you want to know its output, you can use this print statement.
Note that you did not pass the value of platformName. So, it assumed the default value you provided in the init method. However, you can still pass your argument value when an object is created, irrespective of its default value. For example, we have created another instance of EduCBAOnline of the class EduTech with its values:
# Class
class EduTech:
def __init__(self, courseName, platformName="eduCBA"):
self.course = courseName
self.platform = platformName
# Instance creation
eduCBAOnline = EduTech("Python Programming", "Online By EDUCBA")
# Printing instance values
print("This course is", eduCBAOnline.course, "offered on the", eduCBAOnline.platform, "platform.")
Output:
Explanation:
Note that the init method has the default value “EDUCBA,” but we want our “Online By EDUCBA” value. So, it will be changed from its default “EDUCBA” to our new “Online By EDUCBA” value.
Note that you need to print Online by EDUCBA.course and Online by EduCBA.platform because we have set these new values after creating a new instance of EducbaOnline from the EduTech class.
You can set the default to any parameters available in the init method. For example, we have set all the default values of all the parameters:
# Class
class EduTech:
def __init__(self, courseName="AI Engineer", platformName="EDUCBA"):
self.course = courseName
self.platform = platformName
# Instance creation
eduCBA = EduTech()
# Printing instance values
print("This course is", eduCBA.course, "offered on the", eduCBA.platform, "platform.")
Output:
- Class Definition:
- We define an EduTech class.
- It has an __init__ method to initialize attributes course and platform.
- We have passed the parameters courseName and platformName to the __init__ method. The default values for courseName are “AI Engineer” and “EDUCBA.”
- The self.course and self.platform are assigned the values of courseName and platformName, respectively.
- Instance Creation and Output:
- We have created an instance named EDUCBA of the EduTech class.
- There are no arguments or values passed.
- We used dot notation (eduCBA.course and eduCBA.platform) for course and platform attributes accessed and printed.
- The print function printed default values.
- Notes:
- You can use these print statements using the init method.
- When you create a new instance, you can provide your initial values irrespective of default values.
Inheritance and the __init__ Method
1. Inheritance Basics
It is known as inheritance when you create a new class from an existing one. So, you can also inherit its methods and attributes. You also inherited the parent class’s init method from the child class. You can also create variables and processes in the child class, including the init method.
Consider the following class as a parent class:
# Parent Class
class ParentClass:
def __init__(self):
self.parent_attr = "This is parent attribute"
# Child Class
class EduTech(ParentClass):
pass
# Instance creation of child class
eduCBA = EduTech()
# Printing parent value assigned in the init method of parent class
# Using instance of child class
print(eduCBA.parent_attr)
Output:
Explanation:
- Classes Definition:
- There is a parent class, ParentClass, defined.
- It has an __init__ method to initialize the attribute self with the assigned value.
- There is a child class EduTech defined.
- It has no method or variable.
- Instance Creation and Output:
- We have created an eduCBA instance of the child class.
- We did not pass anything in this instance.
- Notes
- The child class does not define variables and methods. Using this instance of the child class, you can access and print variables and methods of the parent class (and also of the child class, if they exist).
- Hence, you can access all the properties and methods (including __init__) of the parent class from the child class’s instance.
Of course, you can also create instances of the parent class separately. For example, we have created an instance eduCBA of the parent class ParentClass:
# Parent Class
class ParentClass:
def __init__(self):
self.parent_attr = "This is parent attribute"
# Child Class
class EduTech(ParentClass):
pass
# Instance creation of parent class
eduCBA = ParentClass()
# Printing parent value assigned in the init method of parent class
# Using instance of parent class
print(eduCBA.parent_attr)
Output:
Explanation:
This is the same example as above, but the only difference is that we have created an instance of a parent class instead of a child class. We accessed and printed the self-attribute of the parent class’s init method.
2. Child Class __init__
If you also want to create the __init__ method in the child class, there is already a __init__ method in the parent class. Then, you can call the __init__ method by using the super() function inside the __init__ method of the child class. So, you can also initialize attributes of the parent class when creating an instance of the child class. For example, we have added the init method to the above child class:
# Parent Class
class ParentClass:
def __init__(self):
self.parent_attr = "This is parent attribute"
# Child Class
class EduTech(ParentClass):
def __init__(self):
super().__init__() # Call parent class __init__ method
self.child_attr = "This is child attribute"
# Instance creation of child class
eduCBA = EduTech()
print(eduCBA.parent_attr) # For Parent attribute
print(eduCBA.child_attr) # For Child attribute
Output:
Explanation:
- Classes Definition:
- There is a parent class, ParentClass, defined.
- It has an __init__ method to initialize the attribute self with the assigned value.
- There is a child class EduTech defined.
- We have initialized the __init__ method of this child class attributes of the child class.
- It calls the __init__ method of the parent class using the super() function to initialize attributes of the parent class.
- Instance Creation and Output:
- We have created an instance named eduCBA of this child class EduTech()
- We have accessed and printed parent_attr and child_attr using the eduCBA instance of the child class EduTech() class.
3. Calling the Parent __init__
As discussed above, we can access the __init__ method of the parent class using the super() function within the __init__ method of the child class. The parent class’s init method can initialize its attributes, and the child class’s init method initializes its attributes.
Considerations and Best Practices
In Python, the __init__ method within a class is unnecessary. However, if you do not create it, Python will automatically create a default constructor for your class. The default constructor does not take action upon creating an instance.
You should always define the __init__ method inside your class. It will give you more control over the initialization process. You can initialize attributes properly, including default values. These are some best practices when using the __init__ method in Python:
- You should always use “self” as the first parameter in the __init__ method. It binds attributes to given arguments.
- You should initialize all the required instance variables. So, when you create an object, it will be in a valid state when created.
- You should do manageable computations and time-consuming tasks in __init__. Instead, you can create separate methods for such tasks to keep __init__ concise.
- You should always use naming conventions. It will have code readability and understanding.
- Always document the __init__ method with a docstring. This will improve code documentation and maintenance.
- Keep the __init__ method short, simple, and easy to read.
Conclusion
In object-oriented programming, like C++, Java, and Python. When you create a class, you create a constructor to initialize the object’s attributes. The __init__ is also known as a constructor in Python. The __init__ method has the keyword “self” as the first parameter that binds given values to its variables. Other parameters are optional in the __init__ method. You can also use the __init__ method of the parent class from the __init__ method of the child class using the super() function. When you call the parent class __init__ method in the child class __init__, it will initialize attributes of the parent class. Note that __init__ does not return anything. You should not do calculation tasks using the __init__ method.
Frequently Asked Questions (FAQs)
Q1: Can you use multiple __init__ methods in a class?
Answer: No. A class can only have one __init__ method. However, you can have multiple classes with their own __init__ methods.
Q2: Is it possible to explicitly call the __init__ method?
Answer: Yes, you can explicitly call the __init__ method. However, the __init__ method automatically calls it an object created.
Q3: What happens if you do not use the self parameter in the definition of __init__ method?
Answer: It will throw a syntax error. The self parameter is necessary as the first parameter in any instance method in Python, including __init__.
Recommended Articles
We hope that this EDUCBA information on “__init__ in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information,