OOP in Python: classes, objects and inheritance

class, __init__, self, attributes and methods, __str__ and inheritance, with a lab where you create objects and call their methods.

Una clase es una plantilla para crear objetos. El método __init__ es el constructor: se ejecuta al crear el objeto y guarda sus datos en self.

class Coche:
    def __init__(self, marca, velocidad=0):
        self.marca = marca
        self.velocidad = velocidad

    def acelerar(self, cuanto):
        self.velocidad += cuanto

    def __str__(self):
        return f"{self.marca} a {self.velocidad} km/h"

c = Coche("Seat")
c.acelerar(30)
print(c)              # Seat a 30 km/h

Lab: build a car

Inheritance

Una clase puede heredar de otra: recibe sus atributos y métodos y puede añadir o cambiar los suyos. class Deportivo(Coche):.

Check what you've learned