Clases y objetos
El tema que suena difícil y no lo es. Vas a entenderlo con un ejemplo, no con definiciones.
Classes and objects
The topic that sounds hard and is not. You will get it from an example, not from definitions.
Imagina que tienes tres jugadores en un juego. Con diccionarios y funciones lo harías así:
Imagine three players in a game. With dictionaries and functions you would do this:
Funciona, pero los datos y las acciones
están separados. Nada impide que alguien cree un jugador sin vidas, o le pase a
recibir_golpe algo que no es un jugador.
Una clase junta las dos cosas: define qué datos tiene algo y qué puede hacer.
It works, but the data and the actions
are separate. Nothing stops someone creating a player with no lives, or passing
recibir_golpe something that is not a player.
A class puts both together: it defines what data something has and what it can do.
La analogía que mejor funciona: la clase es el molde, el objeto es la galleta. Defines el molde una vez y haces todas las galletas que quieras.
class— define el molde. Por convención se escribe con mayúscula inicial.__init__— lo que pasa al crear cada objeto. Se lee "init", de inicializar.self— significa "este objeto en particular". Es el primer parámetro de todos los métodos.
The analogy that works best: the class is the mould, the object is the cookie. Define the mould once and make as many cookies as you like.
class— defines the mould. By convention it starts with a capital.__init__— what happens when each object is created. Short for initialise.self— means "this particular object". It is the first parameter of every method.
Un método es una función que vive dentro de la clase. Se escribe igual, con
self como primer parámetro.
Ya usaste métodos sin saberlo: .append() en listas, .upper() en
textos. Eran métodos de sus clases.
A method is a function living inside the class. Written the same, with
self as first parameter.
You have used methods without knowing: .append() on lists, .upper()
on text. Those were methods of their classes.
Fíjate que al llamar ana.recibir_golpe()
no le pasas nada, aunque el método declare self. Python pone ahí
el objeto automáticamente. Esa es la única rareza de self, y ya la conoces.
Note that calling ana.recibir_golpe() you
pass nothing, even though the method declares self. Python puts
the object there automatically. That is the only oddity of self, and now you know it.
Si necesitas algo parecido pero con extras, no copias la clase: la heredas. La nueva recibe todo lo de la original y le agrega o cambia lo suyo.
super().__init__() llama al constructor del molde original, para no repetir lo
que ya estaba escrito.
If you need something similar but with extras, you do not copy the class: you inherit it. The new one gets everything from the original and adds or changes its own.
super().__init__() calls the original mould's constructor, so you do not repeat
what was already written.
Siendo honestos: no siempre hacen falta. Mucha gente aprende clases y de pronto quiere convertir todo en una, incluso cosas que se resuelven con una función de tres líneas.
Úsalas cuando tengas varias cosas del mismo tipo, cada una con sus propios datos y comportamientos: jugadores, productos, usuarios, vehículos.
Para un script que lee un archivo y calcula un promedio, una función basta y sobra.
Being honest: they are not always needed. Plenty of people learn classes and suddenly want to turn everything into one, even things a three-line function solves.
Use them when you have several things of the same kind, each with its own data and behaviour: players, products, users, vehicles.
For a script that reads a file and works out an average, a function is more than enough.
class, __init__, self, métodos, herencia con
super(), y cuándo conviene no usarlas.
Con esto ya manejas Python a un nivel con el que puedes construir cosas de verdad. Lo que falta son herramientas específicas — archivos, datos, gráficos — pero las ideas del lenguaje ya las tienes todas.
class, __init__, self, methods, inheritance with
super(), and when not to use them.
With this you handle Python at a level where you can build real things. What remains are specific tools — files, data, charts — but you already have every idea in the language.