Python Object Oriented Programming | The __init__ method

The __init__ method is the most important method in a class. This is called when an instance (object) of the class is created, using the class name as a function.

All methods must have self as their first parameter, although it isn’t explicitly passed, Python adds the self argument to the list for you; you do not need to include it when you call the methods. Within a method definition, self refers to the instance calling the method.

Instances of a class have attributes, which are pieces of data associated with them. In our example, Motor instances have attributes color and engine. These can be accessed by putting a dot, and the attribute name after an instance.

In an __init__ method, self.attribute can therefore be used to set the initial value of an instance’s attributes.

Example:

class Motor:
	def __init__(self, color, engine):
		self.color = color
		self.engine = engine

honda = Motor("red", 125)
yamaha = Motor("blue", 150)
suzuki = Motor("orange", 250)

print(suzuki.engine)

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
250
ddn_ro@linux:~/Desktop$

The __init__ method takes two arguments and assigns them to the object’s attributes. The __init__ method is called the class constructor.

Leave a Reply