OOP with Python

Tram Ho

Like the previous post, I went through the basics of variables and data types in python. If you have not seen it, see here . For this part, I will go over about OOP (Object Oriented Programming) in python. Let’s go.


Python is an object-oriented language. So almost everything in Python is an object with properties and methods.

OOP is a programming technique that allows the creation of objects to abstract an actual object (putting real objects into code). Allows programmers to interact with these objects.

An object consists of: attributes and methods.

  • Attributes are the information and characteristics of the object. Example: Cat (color, tail, 2 ears, four legs, …)
  • Methods are the operations and actions that the object can perform. Example: Cat (eating, running, biting, screaming, whining, …)

Class can be understood as a blueprint to create a certain entity, which is a set of many properties specific to the object created from this class. Example: Cat (name, color, tail, ears, legs, …)

An object is an instance of a certain class, created from that class. Example: Ebony cat (named ebony, black, with long tail, 2 ears, 4 legs, ….)

OOP follows a number of basic principles, including 4 principles: TIN encapsulates, Inheritance, closures, Polymorphism.

Fundamental principles of OOP

  • Encapsulation: The related data and methods are packed into a class. That is, each class is built to perform a functional group specific to that class. Hide the information of that class from the public, protected, and private instances of each property and method.
  • Inheritance: This principle allows building a new class based on a class declared before. The child class can reuse the superclass’s properties and methods without declaring it. Depending on the language allows the inheritance of one or more parent classes.
  • Abstraction: generalizing the object’s method regardless of how the method is implemented, represented by the interface (with method names but no method body, when the class impliment the interface then do it).
  • Polymorphism: Polymorphism is represented by a method, actions can be performed in many different ways. For example: cats and dogs are animals, but when performing the ‘barking’ method, the dog barks ‘gogo’, the cat barks ‘distorted cat’. =)

Python is an object-oriented language, so it also follows the basic principles of OOP.

Class, methods, attributes

-In python there are many classes already defined. Since everything in python is an object such as list, tuple, dictionary, string, int … are classes. When we declare variables belonging to these classes, they are objects, if you do not believe, you can use the function type()

In addition to the available classes, we can define separate classes using the class keyword:

In the above example we have created a new object is hl so its type is instant – 1 instance of class helloWorld, and helloWorld is a class – class. Inside the pass class – the syntax for not knowing how to build it, not knowing how to code is optimal and want to leave it for later. But the function, that statement cannot have an empty block, the compiler will error, so just use the pass statement to build an empty block, the compiler will understand and ignore it. Instead of pass we can declare properties and methods here.

– Properties can be understood as a variable in the class, the property describes the properties of an object. In Python, there is a special method called __init__() used to initialize the properties of an object.

The __init__() method is the constructor of all classes, each time an object is created, this method is automatically called. Any Python method must have the first parameter self and then other parameters. self refers to the called object. For example, in the above example when we call pug = dog (‘bug’) then self is the object pug.

In addition to the properties that must be declared when creating a new object, we can declare the properties available to all created classes and do not need to be assigned when declaring. Example: legs

Methods are essentially functions in the class that perform specific jobs:

The available methods are inherited from the original class – magic method

-The __init__() as shown above, initializes the parameters and properties of the class

-In addition, there are __repr__() , __str__() , __del__() , __format__() , __bytes__() , __hash__() , __len__() , __add__() , __call__() , … Understand more about magic method in here

Bagging calculation

In essence in python, the concepts of private, protected, public:

  • with public, it can be accessed anywhere, so the declaration is like a normal function
  • With protected, only the subclass is accessible, the way to declare it by starting with a dash “_”, for example: _age. We will implicitly not use it if it is not a subclass
  • With private, only that class has access, declared by starting with 2 dashes “__”, for example: __age.

Inheritance in python

Inheritance method: class childClass(baseClass):

In the above example we define two classes namely Animal and class Dog. The Dog class inherits from the Animal class, reuses some methods and properties of the Animal class and has its own methods. Above the Dog class inherits the eat () method, inherits and changes the whoAmI () method. In addition, the Dog class has its own method, the run () method. We can see that the dog class reused the legs property and changed its value to 4.

To inherit a class, we put the class name inside the parentheses () right after the class name definition. As the above example is simple inheritance – inherit from a class. In Python, we can have multiple inheritance – allowing from one subclass to inherit from multiple parent classes.

In the above example, Dog class inherits from 2 parent classes, Animal and Entity.

Interface, abstract class

-abstract class: Abstract class allows you to provide default functionality to subclasses. By defining an abstract base class, you can build a common model for a group of subclasses. By default in Python will not provide Abstract class for us to use. But Python has a module called Abstract Base Classes (ABC) to help us do that. This module is in the package abc so we need to import it before using it.

– Keyword @ abstractmethod: to declare that the method below is abstract method

-Interface: In python I do not know if it is true, but I see little documentation about this in python, meaning that the interface is really not necessary because in python there is multiple inheritance. But you can still create an Interface from the same ABC class above.

This article is also long, I just go through the basic parts of OOP, but in detail, it is necessary to learn each part and more carefully. Thank you for your interest

Share the news now

Source : Viblo