-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathchapter5.py
More file actions
673 lines (452 loc) · 17.1 KB
/
Copy pathchapter5.py
File metadata and controls
673 lines (452 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
####################################################
# 5. Classes
####################################################
####################################################
# 5.1 Inicializador y Métodos de instancia
####################################################
from __future__ import annotations
class Rectangulo:
def __init__(self, base: float, altura: float) -> None:
self.base: float = base
self.altura: float = altura
def area(self) -> float:
return self.base * self.altura
rec = Rectangulo(10, 10)
rec.base # => 10
rec.altura # => 10
rec.area() # => 100
Rectangulo(10, 10).area() # => 100
Rectangulo(10, 0).area() # => 0
Rectangulo(0, 10).area() # => 0
####################################################
# 5.2 Variables y Métodos de clase
####################################################
class ArticuloBase:
_last_id: int = 0
def __init__(self, nombre: str = "") -> None:
self.nombre: str = nombre
self.id_: int = self._get_next_id()
@classmethod
def _get_next_id(cls):
cls._last_id += 1
return cls._last_id
art1 = ArticuloBase("manzana")
art2 = ArticuloBase("pera")
art3 = ArticuloBase()
art3.nombre = "tv"
art1.nombre # => "manzana"
art2.nombre # => "pera"
art3.nombre # => "tv"
art1.id_ # => 1
art2.id_ # => 2
art3.id_ # => 3
####################################################
# 5.3 Métodos estáticos
####################################################
class Temperatura:
def __init__(self, region: str, temperatura: float) -> None:
self.region = region
self.temperatura = temperatura
@staticmethod
def celcius_a_farenheit(temperatura: float) -> float: # Sin self
return 32 + temperatura * 9 / 5
@staticmethod
def farenheit_a_celcius(temperatura: float) -> float: # Sin self
return (temperatura - 32) * 5 / 9
temperatura_hoy = Temperatura("Mesopotamia", 35)
assert Temperatura.celcius_a_farenheit(35) == 95 # Invocación desde clase
assert Temperatura.farenheit_a_celcius(95) == 35 # Invocación desde clase
assert temperatura_hoy.celcius_a_farenheit(35) == 95 # Invocación desde instancia
assert temperatura_hoy.farenheit_a_celcius(95) == 35 # Invocación desde instancia
####################################################
# 5.4 Dataclasses
####################################################
from typing import ClassVar
from dataclasses import dataclass, field
import uuid
class Persona:
_dni: int = 0
def __init__(self, nombre: str, edad: int, altura: float, propiedades: Optional[List[str]] = None) -> None:
self.nombre = nombre
self.edad = edad
self.altura = altura
self.propiedades = propiedades or []
self.id_socio = f"{nombre[0].upper()}-{str(uuid.uuid4())[:8]}"
self.dni = str(Persona._get_next_dni()).zfill(8)
def es_mayor_edad(self) -> bool:
return self.edad >= 17
@classmethod
def _get_next_dni(cls) -> int:
cls._dni += 1
return cls._dni
juan: Persona = Persona("Juan", 18, 175.9)
juan.es_mayor_edad() # => True
Persona("Julia", 16, 162.4).es_mayor_edad() # => False
print(juan) # => <__main__.Persona object at 0x000001C90BBF8688>
@dataclass
class PersonaDataClass:
nombre: str
edad: int
sexo: str
peso: float
altura: float
propiedades: List[str] = field(default_factory=list)
id_socio: str = field(init=False)
dni: str = field(init=False)
_dni: ClassVar[int] = 0
def __post_init__(self):
self.id_socio: str = f"{self.nombre[0].upper()}-{str(uuid.uuid4())[:8]}"
self.dni = str(PersonaDataClass._get_next_dni()).zfill(8)
def es_mayor_edad(self) -> bool:
return self.edad >= 18
@classmethod
def _get_next_dni(cls) -> int:
cls._dni += 1
return cls._dni
pedro: PersonaDataClass = PersonaDataClass("Pedro", 18, "H", 85, 175.9)
pedro.es_mayor_edad() # => True
PersonaDataClass("Julia", 16, "M", 65, 162.4).es_mayor_edad() # => False
print(pedro) # => PersonaDataClass(nombre='Pedro', edad=18, sexo='H', peso=85, altura=175.9, propiedades=[], id_socio='P-f642581c', dni='00000001')
####################################################
# 5.5 Sobrecarga de Operadores
####################################################
# Referencia: https://docs.python.org/3/reference/datamodel.html#basic-customization
from typing import List, Optional
@dataclass
class Article:
name: str
def __eq__(self, other: object) -> bool:
if not isinstance(other, Article):
raise NotImplementedError()
return self.name == other.name
def __hash__(self) -> int:
return hash(self.name)
def __str__(self) -> str:
return self.name
def __repr__(self) -> str:
return f"Article('{self.name}')"
@dataclass
class ShoppingCart:
articles: List[Article] = field(default_factory=list)
def add(self, article: Article) -> ShoppingCart:
self.articles.append(article)
return self
def remove(self, remove_article: Article) -> ShoppingCart:
self.articles = [article for article in self.articles if article != remove_article]
return self
def __eq__(self, other: object) -> bool:
if not isinstance(other, ShoppingCart):
raise NotImplementedError()
return set(self.articles) == set(other.articles)
def __str__(self) -> str:
return str(self.articles)
def __repr__(self) -> str:
return f"ShoppingCart({self.articles})"
def __add__(self, other: ShoppingCart) -> ShoppingCart:
return ShoppingCart(self.articles + other.articles)
manzana = Article("Manzana")
pera = Article("Pera")
tv = Article("Television")
# Test de conversión a String
str(ShoppingCart().add(manzana).add(pera)) # => ['Manzana', 'Pera']
# Test de reproducibilidad
carrito = ShoppingCart().add(manzana).add(pera)
assert carrito == eval(repr(carrito))
print(repr(carrito)) # => ShoppingCart([Article('Manzana'), Article('Pera')])
# Test de igualdad
assert ShoppingCart().add(manzana) == ShoppingCart().add(manzana) # => True
print(ShoppingCart().add(manzana)) # => ['Manzana']
# Test de remover objeto
assert ShoppingCart().add(tv).add(pera).remove(tv) == ShoppingCart().add(pera) # => True
print(ShoppingCart().add(tv).add(pera).remove(tv)) # => ['Pera']
# Test de igualdad con distinto orden
assert ShoppingCart().add(tv).add(pera) == ShoppingCart().add(pera).add(tv) # => True
print(ShoppingCart().add(tv).add(pera)) # => ['Television', 'Pera']
# Test de suma
combinado = ShoppingCart().add(manzana) + ShoppingCart().add(pera)
assert combinado == ShoppingCart().add(manzana).add(pera) # => True
print(combinado) # => ['Manzana', 'Pera']
####################################################
# 5.6 Instancias como Functiones (__call__)
####################################################
@dataclass
class Acumulador:
valor_inicial: Union[int, float] = 0
valor: Union[int, float] = field(init=False)
def __post_init__(self):
self.valor = self.valor_inicial
def incrementar(self, valor: Union[int, float]) -> None:
self.valor += valor
acumulador_1 = Acumulador()
acumulador_1.incrementar(5)
acumulador_1.incrementar(10)
acumulador_1.incrementar(-2)
assert acumulador_1.valor == 13
@dataclass
class AcumuladorAlternativo:
valor_inicial: Union[int, float] = 0
valor: Union[int, float] = field(init=False)
def __post_init__(self):
self.valor = self.valor_inicial
def __call__(self, valor: Union[int, float]) -> None:
self.valor += valor
acumulador_2 = AcumuladorAlternativo()
acumulador_2(5)
acumulador_2(10)
acumulador_2(-2)
assert acumulador_2.valor == 13
####################################################
# 5.7 Propiedades y Copia Profunda
####################################################
# Referencia: https://docs.python.org/3/library/copy.html
@dataclass
class Producto:
_nombre: str
_precio: float
@property
def nombre(self) -> str:
return self._nombre.capitalize()
@nombre.setter
def nombre(self, value: str) -> None:
self._nombre = value
@property
def precio(self) -> float:
return round(self._precio, 2)
@precio.setter
def precio(self, value: float) -> None:
self._precio = value
from copy import deepcopy # Biblioteca Estandar
def actualizar_precio(productos: List[Producto], porcentaje_aumento: float) -> List[Producto]:
nuevos: List[Producto] = []
for producto in deepcopy(productos):
producto.precio *= 1 + porcentaje_aumento / 100
nuevos.append(producto)
return nuevos
nombres = ["sábana", "parlante", "computadora", "tasa", "botella", "celular"]
precios = [10.25, 5.258, 350.159, 25.99, 18.759, 215.231]
productos = [Producto(nombre, precio)
for nombre, precio in zip(nombres, precios)]
porcentaje_aumento = 10
productos_actualizados: List[Producto] = actualizar_precio(productos, porcentaje_aumento)
precios_desactualizados: List[float] = [producto.precio for producto in productos]
precios_actualizados: List[float] = [producto.precio for producto in productos_actualizados]
print(precios_desactualizados) # => [10.25, 5.26, 350.16, 25.99, 18.76, 215.23]
print(precios_actualizados) # => [11.28, 5.79, 385.18, 28.59, 20.64, 236.75]
####################################################
# 5.8 Herencia
####################################################
@dataclass
class Animal():
edad: int = 0
def descripcion(self) -> str:
return f"Tengo {self.edad} años"
@dataclass
class Perro(Animal):
raza: str = ""
def descripcion(self) -> str:
return f'Soy un perro y {super().descripcion().lower()}'
terrier = Perro(8, "Yorkshire Terrier")
dogo = Perro(raza="Dogo")
cachorro = Perro(edad=1)
print(terrier.descripcion()) # => Soy un perro y tengo 8 años
####################################################
# 5.9 Constructor (__new__)
####################################################
@dataclass
class Auto:
velocidad_maxima: float
precio: float
def __new__(cls, velocidad_maxima: float, precio: float) -> Auto:
if velocidad_maxima >= 300:
auto = super().__new__(AutoDeportivo)
elif precio >= 100_000:
auto = super().__new__(AutoLujoso)
else:
auto = super().__new__(cls)
auto.velocidad_maxima = velocidad_maxima
auto.precio = precio
return auto
class AutoLujoso(Auto):
...
class AutoDeportivo(Auto):
...
auto_familiar = Auto(170, 3_000)
auto_formula1 = Auto(370, 5_000_000)
auto_famoso = Auto(250, 500_000)
assert isinstance(auto_familiar, Auto)
assert isinstance(auto_formula1, Auto)
assert isinstance(auto_famoso, Auto)
assert isinstance(auto_formula1, AutoDeportivo)
assert isinstance(auto_famoso, AutoLujoso)
####################################################
# 5.10 Clases y Métodos abstractos
####################################################
# Referencia: https://docs.python.org/3/library/abc.html
from abc import ABC, abstractmethod
from typing import final # Python 3.8+
@dataclass
class Item(ABC):
_id: ClassVar[int]
id_: int = field(init=False)
_nombre: str
def __post_init__(self):
self.id_ = self.__class__._get_next_id()
@classmethod
@abstractmethod
def _get_next_id(cls) -> int:
...
@abstractmethod
def mostrar_id(self) -> str:
...
@property
@abstractmethod
def nombre(self) -> str:
...
@nombre.setter
@abstractmethod
def nombre(self, value: str) -> None:
...
@final
def descripcion(self) -> str:
return f"ID: {self.id_} - Nombre: {self.nombre}"
@dataclass
class Ropa(Item):
...
@dataclass
class Material(Item):
_id: ClassVar[int] = 0
id_: int = field(init=False)
_nombre: str
@classmethod
def _get_next_id(cls) -> int:
cls._id += 1
return cls._id
@property
def nombre(self) -> str:
return self._nombre
@nombre.setter
def nombre(self, value: str) -> None:
self._nombre = value
def mostrar_id(self) -> str:
return str(self.id_).zfill(10)
@dataclass
class MaterialLujoso(Material):
def descripcion(self) -> str:
return f'{super().descripcion()} - Material de Lujo'
# item = Item("Item") # => Error
# item = Ropa("Camisa") # => Error
item_lujoso = MaterialLujoso("Formula 1") # => Sin Error - Warning en la declaración
print(item_lujoso.descripcion())
item = Material("Madera")
print(item) # => Material(id_=1, _nombre='Madera')
assert issubclass(type(item), Item)
assert issubclass(type(item), Material)
assert isinstance(item, Item)
assert isinstance(item, Material)
####################################################
# 5.11 Interfaces (Protocols)
####################################################
from typing import Protocol
class Identificable(Protocol):
@property
def nombre(self) -> str:
...
@property
def id_(self) -> int:
...
def get_datos_resumen(objeto: Identificable):
return f"{objeto.id_} - {objeto.nombre}"
madera = Material("Madera")
resumen = get_datos_resumen(madera) # No hay Warning de Tipos
# Incluso si Material no hereda de Identificable
# Incluso si id_ no es una property
# Incluso si
####################################################
# 5.12 Sobrecarga de Métodos
####################################################
from typing import overload, Sequence
@overload
def duplicar(x: int) -> int:
...
@overload
def duplicar(x: Sequence[int]) -> list[int]:
...
def duplicar(x: int | Sequence[int]) -> int | list[int]:
if isinstance(x, Sequence):
return [i * 2 for i in x]
return x * 2
assert duplicar(2) == 4 # Sin Warning
assert duplicar([1, 2, 3]) == [2, 4, 6] # Sin Warning
####################################################
# 5.13 Sobrecarga de Métodos - Caso Especial - Python 3.8+
####################################################
from typing import Union
@dataclass
class Empleado:
sueldo: float
def calcular_sueldo(self, impuesto: Union[int, float]) -> float:
if isinstance(impuesto, int) or impuesto >= 1:
return self.sueldo - impuesto
return self.sueldo * (1 - impuesto)
personal_limpieza_1 = Empleado(10_000)
from functools import singledispatchmethod # Biblioteca Estandar
@dataclass
class EmpleadoAlternativo:
sueldo: float
@singledispatchmethod
def calcular_sueldo(self, impuesto: float) -> float:
raise NotImplementedError()
@calcular_sueldo.register
def _(self, impuesto: float) -> float:
if impuesto >= 1:
return self.sueldo - impuesto
return self.sueldo * (1 - impuesto)
@calcular_sueldo.register
def _(self, impuesto: int) -> float:
return self.sueldo - impuesto
personal_limpieza_2 = EmpleadoAlternativo(10_000)
assert personal_limpieza_2.calcular_sueldo(1500) == 8_500
assert personal_limpieza_2.calcular_sueldo(0.1) == 9_000
assert personal_limpieza_1.calcular_sueldo(1500) == personal_limpieza_2.calcular_sueldo(1500)
assert personal_limpieza_1.calcular_sueldo(0.1) == personal_limpieza_2.calcular_sueldo(0.1)
####################################################
# 5.14 Mixins (Herencia Múltiple)
####################################################
import json
from typing import Any
class JsonSerializer:
def to_json(self) -> str:
return json.dumps(vars(self))
def from_json(self, json_string: str) -> Any:
return json.loads(json_string)
@dataclass
class EmpleadoBaseDeDatos(EmpleadoAlternativo, JsonSerializer):
tabla: str
personal_limpieza_2 = EmpleadoBaseDeDatos(10_000, "Empleados")
assert personal_limpieza_2.to_json() == '{"sueldo": 10000, "tabla": "Empleados"}'
####################################################
# 5.15 Descriptores
####################################################
class Positivo:
def __set_name__(self, _: Any, nombre: str) -> None:
self.nombre_atributo: str = f"_{nombre}"
def __get__(self, objeto: Any, _: Any = None) -> Union[float, int]:
return getattr(objeto, self.nombre_atributo) # type: ignore
def __set__(self, objeto: Any, valor: Union[float, int]) -> None:
if valor < 0:
raise ValueError(f"{self.nombre_atributo} debe ser positivo")
setattr(objeto, self.nombre_atributo, valor)
class Celcius:
def __get__(self, instancia: Any, _: Any = None) -> float:
return (instancia.farenheit - 32) * 5 / 9
def __set__(self, instancia: Any, valor: float) -> None:
instancia.farenheit = 32 + valor * 9 / 5
@dataclass
class MaterialExperimento:
masa: float = Positivo()
temperatura: float = Celcius()
concreto_armado = MaterialExperimento(masa=50, temperatura=100)
assert concreto_armado.masa == 50
assert concreto_armado.temperatura == 100
assert concreto_armado.farenheit == 212 # Warning pero no Error
#oxigeno = MaterialExperimento(masa=-21, -30) # Error -> ValueError: _masa debe ser positivo