Зміст курсу
In-Depth Python OOP
In-Depth Python OOP
4. Polymorphism and Abstraction
Initialization
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.
What is __init__ ?
__init__
is a special method that is used to initialize attributes for a new instance of a class. The __init__
method, which is executed 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 "Bob"
, "Smith"
, and 11
as arguments to the User
class. The __init__
method receives these arguments and utilizes them to define new attributes for the bob
instance.
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.
Note
Further details about methods will be described in subsequent chapters.
We will cover the
self
argument in the next chapter. There is no need to delve into it at this moment.
Все було зрозуміло?