What do init and self do in Python?
__init__ is the initializer method configuring new objects with starting data. self is the instance reference enabling access to the attributes and methods of the class.
Example:
Remember: __init__ gets the object ready, self is the object's mirror image inside the class blueprint.
self: Python's personal pronoun
Self acts as a reference to the current object instance. It's always the first parameter in instance methods, bridging between instance variables and methods. Here's why self matters:
selfshould always be the first parameter in a method. Without it, instance attributes and methods become inaccessible within the method.- Treat
selfas a passport for an instance. It identifies instance-specific data and can be used within the method to access or modify this data. - Although
selfis not a keyword in Python, it is a widely agreed-upon convention and should be followed for clarity.
__init__: The object builder
The __init__ method is Python's version of a constructor. It builds your instance from scratch, starting the moment you create an instance. Here's why __init__ is crucial:
__init__sets the initial values for an instance. You can therefore customize these values upon creation.- Be careful when adding extra parameters into
__init__— they must be handled correctly to avoid errors, such as aTypeError.
Monty Python's guide to house-building
Script: __init__ and self in Python are like building a house:
TL;DR:
A closer look at self and __init__
self in context
Instance variables are unique to each object and using self retains this uniqueness. Here's an example:
Modifying the attributes of an object after creation doesn't affect other instances, proving the uniqueness of instance variables.
Behind the scenes with __init__
Although __init__ starts the ball rolling for an instance, __new__ has already done some of the ground work beforehand:
__new__requests the memory required for the new instance.__init__then sets the initial state of the instance.- Python splits the construction responsibilities to make it easier for you. In most cases,
__new__works behind the scenes and you won't need to think about it.
Comparing class and instance variables
It's vital to understand the differences between class and instance variables:
- Class variables hold shared values for all instances of the class.
- Instance variables are tied with
self, so they belong to individual objects, maintaining their own unique values.
For clarity, let's bring code to the equation:
Memory tip: Class variables are communal; instance variables are individualistic.
Was this article helpful?