Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/marioaje/Python/llms.txt

Use this file to discover all available pages before exploring further.

Object-Oriented Programming (OOP) is a programming paradigm that organises code around real-world entities. As the course source code describes it, a class is “un segmento de codigo que nos permite simplificar el desarrollo, reutilizar codigo” — a segment of code that lets you simplify development and reuse logic. Instead of writing separate variables and functions for every person, every product, or every calculation, you define a class once and then create as many objects (instances) of that class as you need.

Section 1 — Class Anatomy

Every Python class is built from three essential ingredients:
Building blockPurpose
NameHow the class (and its objects) are identified in your code. Defined with the class keyword.
__init__The initialiser — runs automatically when a new object is created. Sets up the object’s starting state.
AttributesVariables that belong to an instance, declared as self.attribute_name inside __init__.
MethodsFunctions defined inside the class that operate on the instance’s data. Always receive self as their first argument.
What is self? The word self is a reference to the current instance of the class — it is the object that is calling the method. Python passes it automatically behind the scenes whenever you call a method on an object. By convention it is always the first parameter in any method definition, though the name self is not a reserved keyword — it is simply the universally accepted convention.

Section 2 — The persona Class

The main class used throughout Week 3 is persona. It demonstrates __init__, instance attributes, getter-style methods, and a setter-style method all in one file.
semana3/clases.py
# las clases son segmento de codigo,
# que nos permite simplificar el desarrollo
# reutilizar codigo

# 1-Un nombre (como se llama el archivo, el programa y modulo)
# class, palabra reservada.
class persona:
    # inicializador del programa, clase
    # self hacia mi mismo, self es palabra reservada
    def __init__(self, cedula, nombre, apellido):  # lo que esta adentro se le conoce como atributos
        # declaracion de atributos o variables asignadas a la clase
        self.cedula = cedula
        self.nombre = nombre
        self.apellido = apellido
        self.version = "2023"

    # funciones de retorno
    def devuelvacedula(self):
        print("la cedula es: ", self.cedula)

    def regresameelnombre(self):
        print("el nombre es:", self.nombre)

    def regresameversion(self):
        print("version es:", self.version)

    # funciones de ajuste, de cambio de valores.
    def cambiocedula(self, cedula):
        self.cedula = cedula
Breaking it down:
  • __init__ accepts three arguments (cedula, nombre, apellido) in addition to self, and stores them as instance attributes. version is a fixed attribute — every persona object starts with "2023".
  • devuelvacedula(), regresameelnombre(), and regresameversion() are getter-style methods — they print the current value of an attribute.
  • cambiocedula(self, cedula) is a setter-style method — it accepts a new value and updates the instance’s cedula attribute in place.

Section 3 — Instantiating Objects

A class is just a blueprint. To use it you must create one or more instances (objects). The source file shows the full workflow — creating objects, calling getter methods, and calling a setter method:
semana3/clases.py
# aca se trabaja con la clase
# nueva variable, del tipo clase
variablea = persona("123", "Mario", "Jimenez")
variableb = persona(9, "Isaac", "Jimenez")

variablea.devuelvacedula()      # la cedula es:  123
variablea.regresameelnombre()   # el nombre es: Mario
variablea.regresameversion()    # version es: 2023

nuevacedula = 32166
variablea.cambiocedula(nuevacedula)
variablea.devuelvacedula()      # la cedula es:  32166

variableb.devuelvacedula()      # la cedula es:  9
1

Create an instance

Call the class like a function, passing the arguments that __init__ expects:
variablea = persona("123", "Mario", "Jimenez")
Python creates a new persona object and stores it in variablea.
2

Call getter methods

Use dot notation to call a method on the object:
variablea.devuelvacedula()    # prints: la cedula es:  123
variablea.regresameelnombre() # prints: el nombre es: Mario
3

Update an attribute with a setter

Pass the new value to a setter method to change stored data:
nuevacedula = 32166
variablea.cambiocedula(nuevacedula)
variablea.devuelvacedula()    # prints: la cedula es:  32166
4

Each instance is independent

variableb was created separately and retains its own data:
variableb.devuelvacedula()    # prints: la cedula es:  9

Section 4 — The Persona Class: Getters and Setters

The Semana 2/poo.py file introduces an uppercase Persona class that formalises the getter/setter pattern with the conventional get/set naming:
Semana 2/poo.py
# Personas
# Clase persona, atributos y funciones
class Persona:
    # Primero se crea el inicializador de los datos
    def __init__(self, nombre):
        self.nombre = nombre
        # Se necesitan 6 nuevos atributos:
        # email, apellido, fecha nacimiento, telefono, provincia

    # Creo la funcion que muestre los datos
    def getNombre(self):
        print(self.nombre)

    # Cambiar o ajustar los datos
    def setNombre(self, nombre):
        self.nombre = nombre

# evalua formato de correo electronico
# Se requieren los set y gets: email, apellido, fecha nacimiento, telefono, provincia
# Se requiere una funcion que calcule la edad, con base a la fecha de nacimiento
# se necesita una funcion que imprima toda la informacion agregada.


Usuario = Persona("Mario")
Usuario.getNombre()   # prints: Mario

Getter vs Setter — at a glance

AspectGetter (getNombre)Setter (setNombre)
PurposeRead the current value of an attributeWrite / update the value of an attribute
ParametersOnly selfself + the new value
Returns / side-effectPrints (or returns) the stored valueUpdates self.attribute in place
Typical namingget + attribute nameset + attribute name
Example callUsuario.getNombre()Usuario.setNombre("Isaac")
The get/set naming convention comes from languages like Java. In Python it is perfectly valid, but the language also supports properties (@property) as a more Pythonic alternative. For a beginner course the explicit get/set style is clear and easy to read.

Section 5 — The calculadora Class

semana3/calculadora.py shows a class that accumulates a running total through repeated calls to suma:
semana3/calculadora.py
# funcion de suma

# funcion de resta

class calculadora:
    def __int__(self):
        self.resultado = 0.0

    def suma(self, valor1):
        self.resultado += valor1

    def retornarresultado(self):
        return self.resultado


nuevavariable = calculadora()
capturavalor1 = 3
capturavalor2 = 9
nuevavariable.suma(capturavalor1, capturavalor2)
nuevavariable.resultado
Key observations about this class:
  • __int__ vs __init__ — the initialiser here is named __int__ (a typo for __init__). Because __int__ is not the constructor, self.resultado is never automatically set to 0.0 when a new object is created. The correct special method name is __init__.
  • suma(self, valor1) accepts exactly one extra argument and uses += to add it to self.resultado, accumulating a running total across multiple calls.
  • retornarresultado(self) uses return to hand the total back to the caller — making the result usable elsewhere in the program.
  • The script at the bottom contains two bugs carried over from the source: __int__ is never invoked, and nuevavariable.suma(capturavalor1, capturavalor2) passes two arguments to a method that only accepts one, which raises a TypeError at runtime.
The source file semana3/calculadora.py contains two bugs worth noting:
  1. __int__ instead of __init__ — the constructor dunder is misspelled, so self.resultado is never initialised. Always double-check the spelling of dunder methods (__init__, __str__, __repr__).
  2. suma called with two argumentssuma(self, valor1) only accepts one value, but the script calls nuevavariable.suma(capturavalor1, capturavalor2). This raises a TypeError: suma() takes 2 positional arguments but 3 were given. The fix is either to add a valor2 parameter to the method, or to call suma once per value.

Build docs developers (and LLMs) love