Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Initialization | OOP Concepts
In-Depth Python OOP
course content

Course Content

In-Depth Python OOP

In-Depth Python OOP

1. OOP Concepts
2. Inheritance
3. Encapsulation
4. Polymorphism and Abstraction
5. Magic Methods

bookInitialization

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.

123456789
class User: def __init__(self, name, surname, age): self.name = name self.surname = surname self.age = age bob = User("Bob", "Smith", 11) print(bob.name, bob.surname, bob.age)
copy

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.

What is the purpose of the \_\_init__ method?

What is the purpose of the __init__ method?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 4
some-alt