Classes & objects · Clases y objetos
A class is a blueprint
- A class defines a new kind of thing — a user-defined type.
- An object is one item made from that class.
- One
Dogclass can make many dog objects, each with its own data.
Una clase es una plantilla
- Una clase define un nuevo tipo de cosa — un tipo definido por el usuario.
- Un objeto es un elemento creado a partir de esa clase.
- Una
Dogclase puede crear muchos objetos Perro, cada uno con sus propios datos.
init and attributes
__init__is a special method that runs when you make an object.selfrefers to the object being made.- Values stored on
selfare the object's attributes (its data).
init y atributos
__init__es un método especial que se ejecuta cuando creas un objeto.selfhace referencia al objeto que se está creando.- Los valores almacenados en
selfson los atributos del objeto (sus datos).
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(2, 5)
print(p.x)
print(p.y)
Methods
- A method is a function defined inside a class.
- Its first parameter is always
self, the object it works on. - Call it with a dot:
object.method().
Métodos
- Un método es una función definida dentro de una clase.
- Su primer parámetro siempre es
self, el objeto sobre el que actúa. - Llámalo con un punto:
object.method().
class Greeter:
def __init__(self, name):
self.name = name
def hello(self):
return "Hi, " + self.name
g = Greeter("Sam")
print(g.hello())
Enumerated types
- An enumerated type is a fixed set of named values.
from enum import Enumlets you define one as a class.- It is clearer than using loose numbers like
1,2,3.
Tipos enumerados
- Un tipo enumerado es un conjunto fijo de valores nombrados.
from enum import Enumte permite definir uno como una clase.- Es más claro que usar números sueltos como
1,2,3.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.GREEN)
print(Color.GREEN.value)
In Cambridge pseudocode
- A
CLASSblock lists its data and aNEWconstructor.
En pseudocódigo de Cambridge
- Un bloque
CLASSenumera sus datos y un constructorNEW.
CLASS Point
PRIVATE X : INTEGER
PRIVATE Y : INTEGER
PUBLIC PROCEDURE NEW(startX : INTEGER, startY : INTEGER)
X ← startX
Y ← startY
ENDPROCEDURE
ENDCLASS
DECLARE p : Point
p ← NEW Point(2, 5)
Common mistakes
- Every method takes
selfas its first parameter. __init__runs automatically when you create an object.
Errores comunes
- Cada método toma
selfcomo su primer parámetro. __init__se ejecuta automáticamente cuando creas un objeto.
Now you try
- Define each class with
__init__and any methods it needs. - Press Check answer to test your code.
Ahora tú prueban
- Define cada clase con
__init__y cualquier método que necesite. - Pulsa Check answer para probar tu código.
Define a class Dog whose __init__ takes name and · y age and stores them as attributes self.name and · y self.age. · Define una clase Dog cuyo __init__ reciba name y age y los almacene como atributos self.name y self.age.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Define a class Rectangle with __init__(self, width, height) and a method area(self) that returns · retornos width * height. · Define una clase Rectangle con __init__(self, width, height) y un método area(self) que devuelva width * height.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Define a class BankAccount. __init__ sets self.balance to · hasta 0. Add deposit(self, amount) to add money and withdraw(self, amount) to take it away. · Define una clase BankAccount. El __init__ establece self.balance en 0. Añade deposit(self, amount) para agregar dinero y withdraw(self, amount) para retirarlo.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.