Contents:

Master Python development with a free course ➞ Take a free Python course and learn how to create Telegram bots, web parsers, and websites from scratch under the guidance of a Sber expert.
Learn moreObject-oriented programming methodology has become the standard in most large companies, as it significantly simplifies the development process. However, despite this, many newcomers to programming are intimidated by its development. In this article, we will try to demonstrate that this approach is actually not that difficult.
Why OOP Was Invented
In object-oriented programming (OOP), the fundamental element is the object. This object can be thought of as a unique container that holds both data and describes the operations that can be performed on that data.
To understand the value of objects and the purpose for which they were created, it's worth comparing object-oriented programming with a procedural approach to development. Within the latter approach, all program code can be classified into two categories: the main application and auxiliary functions. These functions can be called both by the main code and by other functions.

This programming methodology has a significant drawback - the code components are highly interdependent. For example, the main program initiates a call to one function, which in turn calls another, which in turn calls a third. Let's assume that the second function can be called not only by the main program, but also by several other functions simultaneously. This entire confusing sequence can be represented schematically on a graph:

When making changes to one of the functions, it may turn out that the rest of the code will not be able to cope with it - and, as a result, errors will occur. As a result, other parts that, in turn, depend on various functions will also have to be modified. Ultimately, it will be much more efficient to develop a completely new program from scratch.
In procedural programming, it is often necessary to repeat code and create functions that differ only in minor respects. This is done, for example, to ensure interaction between various program components.
In object-oriented programming (OOP), the approach to code organization is different: instead of connecting functions to the main program, objects are used that contain both their own variables and functions. This allows for a more structured hierarchy. Within objects, variables are usually called fields or attributes, and functions are called methods.

Each object functions independently and has all the necessary functionality, Thus, damage to one of the objects will not affect the others. Moreover, even with a complete restructuring of the internal contents of an object, provided its behavior is preserved, the code will continue to function without failures.
How Classes Work
In object-oriented programming, each element is created based on a specific class, which is an abstract model. This model details both the structure of the object and the actions that can be performed with it.
Consider a class called "Cat", which includes characteristics such as "breed", "color", "age", as well as actions that the cat can perform: "meow", "purr", "wash" and "sleep". By setting specific values for these characteristics, we can create specific instances of this class.
Let's say:
- Abyssinian breed.
- Color = red.
- Age = 4.
Thus, we have the ability to create an infinite number of different cats.

Thus, any instance of the "Cat" class—regardless of whether it is red, gray, or black—will be able to meow, purr, wash itself, and sleep if we implement the necessary methods.
Object-Oriented Programming Basics in Python
Object-oriented programming basics are based on four key concepts: encapsulation, inheritance, polymorphism, and abstraction. With that in mind, let's look at the "Cat" class as an example to illustrate these principles in action:
The __init__ method initializes the class. It is activated immediately after the instance is created to set values for dynamic attributes. The self argument is a reference to the current object, providing access to the attributes and methods used in the process. In other programming languages, the equivalent of self is the this keyword.
Note 1: Although using the keyword self is a common practice, its use is not required. You can replace it with any other name. However, it is worth considering that such a replacement may cause confusion for those examining your code.
Note 2: It is common practice to use capital letters for class names, while object names are written with lowercase letters.
We have developed a Cat class in which we have defined three main attributes: breed, color, and age. We've also implemented two methods that allow our cat to make sounds: meowing with the meow() method and purring with the purr() method.
Let's create several instances of our class:
Wonderful! Now that we've laid the groundwork, let's move on to learning the basics of object-oriented programming.
Controlling access to an object's data is necessary to prevent users from accidentally changing it, which can lead to errors. For this reason, developers create special methods that allow interaction with data from outside the class without compromising the internal structure and integrity.
Let's turn to our cats. We can allow the "age" attribute to change, but only in the direction of increase. As for the "breed" and "color" attributes, it's better to leave them read-only - the cat's breed remains unchanged, and the color can change, but not at its discretion.
In our Cat class, we set all attributes as public. Let's make the necessary changes.
The code has become a bit more complex, but we'll clarify all the details now. First, we made all the attributes inaccessible from the outside by adding the _ symbol before them. This sign tells the interpreter that these variables can only be used within class methods.
To continue accessing the attributes, we implement this using the @property decorator and create separate methods for each of the attributes—breed, color, and age. In these methods, we return the values of the private attributes, which makes them read-only.
Finally, we need to allow users to change the cat's age. To do this, we'll use @age.setter and define the age method again, adding a simple condition in its body and returning the value of the corresponding attribute.
Now let's create an object of this class:
Define the attribute values:
Let's try making changes to the age attribute:
Everything went great. Now let's move on to changing another attribute:
The error occurred because changes to this attribute were prohibited.

Read also:
Encapsulation and access modifiers: part three of the object-oriented programming guide programming.
Classes have the ability to inherit their properties and methods from parent classes. Let's consider a situation where we need to create a "Domestic Cat" class. This class will be almost the same as the "Cat" class, but it will include additional attributes, such as "owner" and "nickname", as well as a new method called "beg for a treat".
To make "Domestic Cat" an inheritor of the "Cat" class, simply specify this in the code and add the necessary attributes and methods. All other functionality will be automatically inherited from the parent class.
I propose to introduce a new class:
In the first line of code, we inherit all methods and properties from the Cat class. In order for everything to be created correctly, you need to call the super() method inside the __init__() method and initialize the attributes of the parent class through it. This is why we pass parameters such as "breed," "color," and "age" to this method.
In addition to the properties inherited from the parent class, the child class also has unique attributes: "owner" and "name." These attributes are intended exclusively for use in this class and will not be available to the parent class.
The child class's attributes were initially set to private, and individual methods were created for them. In addition, we implemented the getTreat() method, which is not present in the parent class.
Let's create an instance of the class:
We observe that both the new and traditional methods function effectively. The inheritance process has been completed successfully.

Read also:
Inheritance and a little about polymorphism: the fifth part of the guide to object-oriented programming.
This principle makes it possible to use the same commands for objects belonging to different classes, even if their implementations differ. For example, we have a class "Cat" and a completely independent class "Parrot", both of which have a "sleep" method. Although the sleep process in these animals is different (a cat usually curls up into a ball, while a parrot prefers to sit on a perch), the same command can be used to perform this function.
Suppose we have two classes - "Cat" and "Parrot".
Imagine that we have a method that expects to receive an object with a specific method called sleep.
Let's check how this will work.
Despite the differences between the classes, methods with the same names function in a similar way. This phenomenon is called polymorphism.

Read also:
Polymorphism in object-oriented programming (OOP) is a key concept that allows objects of different classes to handle the same message differently. This is achieved through the ability of different classes to provide their own method implementations, providing flexibility and extensibility for code.
Method overloading is a mechanism that allows for the creation of multiple versions of the same method within a single class. These versions can differ in the number or type of parameters, allowing the same method to be called with different arguments, thereby improving the readability and usability of code.
As for operator overloading, this approach allows for the modification of the behavior of standard operators for user-defined data types. For example, it is possible to define how the addition operator will work with instances of its own classes, which makes the code more intuitive and maintainable.
Thus, polymorphism, together with method and operator overloading, plays an important role in creating more versatile and adaptable software, allowing developers to effectively manage complexity and maintain a high degree of abstraction.
When designing a class, we reduce it to the necessary attributes and methods that are relevant in a given context, avoiding unnecessary detail and ignoring less important elements. For example, all predators have a "hunt" method, therefore, any animal belonging to this category will have the hunting ability by default.
Let's analyze the Predator class:
This class unites all representatives of the animal world related to predators, including, for example, cats:
A cat has its own characteristics: "name" is name, and "color" is color. However, being a descendant of predators, she has hunting skills:

Read also:
Abstract classes and interfaces: the sixth part of the guide to object-oriented programming.
Practical Application of Object-Oriented Programming in Python
Let's continue our creative work and develop new classes.
Imagine this: your friend has received an invitation to a luxurious event at an elite club. There is a rather unusual etiquette: at different points in the evening, participants are required to consume strictly specific drinks. Moreover, each of them must be consumed depending on the situation - either in small portions of 10 ml, or slightly larger ones of 20 ml, or in one gulp, emptying the remaining contents of the glass. Moreover, it is worth noting that the sip size for the same drink can unexpectedly change during the course of the party.
You learn a multitude of confusing rules and decide to help your friend, but you can only communicate with him through an earpiece. In this case, your friend becomes the intermediary with whom you interact when it comes to drinks.
Let's start by developing a class called Drink.
Each drink has certain characteristics, such as a name, a price in rubles, and a volume in milliliters. Let's assume that at our party we use a glass with a fixed volume of 200 ml, while the other parameters can vary depending on the specific drink.
Thus, the volume can be considered a static parameter that remains the same for all instances of the class. In contrast, the name and price are dynamic characteristics, since they do not apply to the entire class as a whole, but to individual objects, and their values are set only after these objects are created.
We will create a coffee object, which will represent an instance of the Drink class. In the context of our example, the process of creating this new object can be viewed as placing an order for a freshly brewed drink.
Now we have a coffee object, which includes a static attribute called volume, inherited from the Drink class, as well as dynamic attributes called name and price, set during the creation of this object. Let's try to access these attributes:
Since static attributes are set at the class level, they can be accessed not only through object instances, but also directly through the class itself.
We will not be able to access dynamic attributes.
So, you have placed an order for a drink, and now you need to take some action. Since you are communicating through an earpiece, you do not have visual control over the state of your friend's drink. In this situation, it is worth asking him to update you on the current situation. To implement this, we will add a new method to the Drink class:
The company takes its first sip. Let's give a command to our friend to connect to us. To do this, we need to add another attribute—remains—which will indicate how many milliliters of drink are left. Initially, this value will be equal to the full volume of the container. Then, we'll write a method that will inform the user exactly how much to drink, following the rules of etiquette:
Access Types in Python
To avoid having to constantly check whether there's enough drink for the next sip, we'll create a helper method, _is_enough. After this, we'll update the sip method and additionally implement the small_sip and drink_all methods.
It's also worth noting one important point: in the line coffee.remains = 10 , we've made an external change to the object, assigning its remains attribute the value 10. This is possible because in Python, all attributes and methods are publicly accessible by default.
Object-oriented programming (OOP) provides different access levels that help control interaction with the internal components of a class. These levels include public, protected, and private. Protected methods and attributes are accessible not only within the class itself but also in its subclasses. In contrast, private members can only be used within the class and cannot be called even from derived classes.
The Python programming language uses the following convention: protected attributes and methods are preceded by a single underscore (_example), while private members are preceded by a double underscore (__example). In particular, in the _is_enough method, we used a single underscore to indicate its protected status.
In Python, simply marking attributes and methods as protected or private does not prevent them from being accessed from outside the program. We can still call the _is_enough method from anywhere in the program:
Private attributes and methods cannot be called directly, but there is a way to work around this limitation:
It's important to note that ignoring access levels is considered a violation of a key principle of object-oriented programming: encapsulation. Therefore, while technically possible, Python practitioners have come to the agreement not to interact with protected and private methods from the outside.
Therefore, we will make the volume and remains attributes protected to remind them that they should only be used within the Drink class and its subclasses. The structure now looks like this:
Python Inheritance Principles
The party is gaining momentum when something unexpected happens. Your friend, who has already managed to adapt to the atmosphere and even began to enjoy the event, suddenly whispers into your earpiece that the evening is getting tense again. "They announced juice time!" he reports, alarmed. "Every juice has its own unique flavor, it's hard to figure it out!"
Absolutely correct. Houston, we've run into a problem. At first glance, juice appears to be a regular beverage: it can be sipped or consumed in one gulp, and it has its own price and volume. However, as Mr. Shnurov noted, there's one important nuance: unlike other drinks, juice has a unique attribute that's not typical of the Drink category—the flavor of the fruits or berries from which it was made.
Don't panic: even in the most complex situations, there are always at least two solutions. We could, of course, simply create an exact copy of the Drink class and make the necessary changes. However, we will choose a more elegant approach - we will develop a Juice class that will inherit the properties of the Drink class.
It is important to note that the derived class does not have the ability to directly access the private methods and attributes of the parent class.
We create an instance of the Juice class and implement the methods inherited from the parent Drink class.
The Drink class, being a parent, granted its derived class access to its attributes and methods, which saved us from having to rewrite them.
Now let's pay attention to the name attribute. In the Drink class, when we had the ability to order various drinks - from coffee and tea to kvass and cocktails - it was logical to specify the name each time. However, in the Juice class, the name is always the same: "juice". This raises the question: why request the name attribute every time you order juice?
In the Juice class, we will change the __init__ method, setting the value of the name attribute to "juice". After that, let's create an instance of apple juice again:
When an apple_juice object is created, a series of sequential actions occur, which include initializing its properties and setting the values associated with this object. First, an instance is created, which may include certain parameters, such as ingredients, volume, or even information about the manufacturer. Then, the appropriate values are assigned to these parameters, which allows the apple_juice object to become a full-fledged representative of its class. This process may also include executing various methods that provide the necessary functionality and allow the object to interact with other elements of the system.
1. We create an instance of the Juice class, passing the price and taste values as arguments to its initializer.
The Juice class initializer uses the super() function to call the initializer of its parent class, Drink.
The Drink class initializer requires two arguments: name and price. The name argument receives the value of the static attribute _juice_name, which was defined in the Juice class. While the value for the price argument is retrieved from the Juice class initializer,
The Drink class constructor sets the values for the name, price, and _remains attributes.
The Juice class constructor sets the value for the taste attribute.
If you're still having trouble understanding where the data comes from and where it goes, take a look at the diagram below. It highlights the routes by which attributes are assigned their values in different colors:

So, you told your friend that there is no need to declare your wanting juice—otherwise, others might think he's a man with rustic habits. Everyone already knows he's not asking for compote. However, notice what happens when we ask him to provide information about an object of the Juice class:
He tells us that he drinks juice, but doesn't specify which one. To extract more information from our friend, we should modify the drink_info method from the parent class:
Thus, we've implemented the principle of polymorphism. Regardless of what drink our friend prefers—be it coffee or juice—we can get information about his choice from him using the same drink_info command. And our friend will decide how to respond: if he enjoys juice, he'll tell us about its taste, and if he enjoys any other drink, he'll share its name.
It's important to note that in Python, all classes automatically inherit from the object superclass, allowing them to access its attributes and methods. Such inherited methods include, for example, the built-in functions __new__, __init__, __del__, and several others.
The party is slowly winding down, and so far your friend has managed to remain unnoticed. The days of sipping are over, and now everyone can enjoy whatever they like. It seems like it's time to relax. However, as you already know, we have a great host and exciting contests: guests are surprised by a new idea. People are asked to sit at tables based on the price of their drinks. Everyone starts shouting out the prices of their glasses, and the waiters direct them to new seats. Your friend is still confused, but we'll be sure to help him out.
Since it's possible to specify a price for any drink, we'll create a tell_price method in the Drink class, which will then automatically be available in the Juice class, which is a child class.
Now we'll make sure it works with both Drink and Juice objects.
Dear colleagues, imagine this: your friend leaves a party with a new girlfriend and an invitation to the next event. And all of this became possible thanks to you and the principles of object-oriented programming.
