Python as an OOP language
In this section, we will review Object-Oriented Programming and inheritance in Python.
Object-Oriented programming is one of the paradigms most used today. While it fits a lot of situations that we can find in day-to-day life, in Python, we can combine it with other paradigms to get the best out of the language and increase our productivity while maintaining an optimal code design.
Python is an object-oriented language and allows you to define classes and instantiate objects from these definitions. A block headed by a class statement is a class definition. The functions that are defined in the block are its methods, also called member functions.
The way Python creates objects is with the class keyword. A Python object is a collection of methods, variables, and properties. You can create many objects with the same class definition. Here is a simple example of a protocol object definition:
You can find the following code in the protocol.py file.
class protocol(object):
def __init__(self, name, number,description):
self.name = name
self.number = number
self.description = description
def getProtocolInfo(self):
return self.name+ " "+str(self.number)+ " "+self.description
The __init__ method is a special method that, as its name suggests, act as a constructor method to perform any initialization process that is necessary.
The first parameter of the method is a special keyword and we use the self identifier for reference the current object. It is a reference to the object itself and provides a way to access its attributes and methods.
The self parameter is equivalent to the pointer that can be found in languages such as C ++ or Java. In Python, self is a reserved word of the language and is mandatory, it is the first parameter of conventional methods and through it you can access the attributes and methods of the class.
To create an object, write the name of the class followed by any parameter that is necessary in parentheses. These parameters are the ones that will be passed to the __init__ method, which is the method that is called when the class is instantiated:
>>> protocol_http= protocol("HTTP", 80, "Hypertext transfer protocol")
Now that we have created our object, we can access its attributes and methods through the object.attribute and object.method() syntax:
>>> protocol_http.name
>>> protocol_http.number
>>> protocol_http.description
>>> protocol_http.getProtocolInfo()