Object-Oriented Programming is a programming paradigm based on the concept of “objects”.
These are groupings that represent real-world entities with their own characteristics (attributes) and behaviors (methods).
In OOP, objects interact with each other through messages, which allows for a more natural modeling of complex systems.
If you want to learn more about object-oriented programming, here is the link to the Object-Oriented Programming Course.
Definition of a Class in Python
In Python, classes are defined with the keyword class
followed by the class name and a colon (:).
A class is a template or a “mold” for creating objects. It defines the properties and behaviors that the objects created from it will have.
class Persona:
def __init__(self, nombre, edad):
self.nombre = nombre
self.edad = edad
def saludar(self):
print(f"Hola, mi nombre es {self.nombre} y tengo {self.edad} años.")
The
__init__
method is a special method called “constructor,” which is automatically executed when creating a new object of the class. Here, we initialize thenombre
andedad
attributes.The
saludar
method is an instance method that displays a greeting with the person’s name and age.
Attributes are variables that belong to an object and represent its characteristics or properties *(they can be of any data type (such as numbers, strings, lists, etc).
In the previous example, nombre
and edad
are attributes of the persona
object.
Methods are functions that belong to an object and can operate on its attributes *(they can perform operations such as modifying attribute values or interacting with other objects).
In the example, saludar
is a method of the persona
object.
Creating Instances
An instance is each of the “examples” we create from a class. Each instance will have its own values for the attributes defined in the class.
To create an object from a class, simply call the class name followed by parentheses.
For example, once we have the Persona
class, we can create instances of this class like this,
luis = Persona("Luis", 30)
In this case, we have created an object luis
from the Persona
class, with the values “Luis” for the nombre
attribute and 30 for the edad
attribute.
Accessing Attributes and Methods
To access both the attributes or methods of an instance, we simply use the access operator .
on the variable that contains the instance.
For example like this,
luis = Persona("Luis", 30)
ana = Persona("Ana", 25)
luis.edad = 35; # Change Luis's age to 35
ana.edad = 28; # Change Ana's age to 28
luis.saludar() # Output: Hola, mi nombre es Luis y tengo 35 años.
ana.saludar() # Output: Hola, mi nombre es Ana y tengo 28 años.