In-Depth Python OOP
Instances are commonly created with specific parameters that distinguish them from one another. For instance, let's consider the class "User" and its instances, such as John and Bob, who have distinct names, surnames, and ages. Now, let's explore how we can set these parameters when creating an instance.
__init__ is a special method that is used to initialize attributes for a new instance of a class. The
__init__ method, which is executed each time we create a new instance of a class.
As a reminder, creating a new instance involves using the class name and parentheses
(). The purpose of the
__init__ method is to receive values as arguments within these parentheses and assign these values to the attributes of the newly created instance.
In the provided example, we have defined the
__init__ method, which is executed every time a new instance of the class is created. When we create the
bob instance, we pass the values
11 as arguments to the
User class. The
__init__ method receives these arguments and utilizes them to define new attributes for the
User.age should raise an
AttributeError because the
User class does not have any attributes defined. The
__init__ method, as mentioned earlier, is responsible for defining attributes for each instance of the class, not for the class itself.
Further details about methods will be described in subsequent chapters.
We will cover the
selfargument in the next chapter. There is no need to delve into it at this moment.
What is the purpose of the init method?
Select the correct answer
Everything was clear?