forked from fiemcasals/Programacion_II
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10_abc_protocols.py
More file actions
31 lines (24 loc) · 812 Bytes
/
10_abc_protocols.py
File metadata and controls
31 lines (24 loc) · 812 Bytes
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
# 10_abc_protocols.py — Clases abstractas vs Protocol (duck typing)
from abc import ABC, abstractmethod
from typing import Protocol
class Recurso(ABC):
@abstractmethod
def abrir(self) -> None: ...
@abstractmethod
def cerrar(self) -> None: ...
class Archivo(Recurso):
def __init__(self, ruta: str):
self.ruta = ruta
self._abierto = False
def abrir(self) -> None:
self._abierto = True
def cerrar(self) -> None:
self._abierto = False
class SoporteLog(Protocol):
def write(self, msg: str) -> int: ...
def loggear(logger: SoporteLog, msg: str) -> None:
logger.write(msg + "\n")
if __name__ == "__main__":
a = Archivo("demo.txt")
a.abrir(); a.cerrar()
loggear(logger=open(__file__, "a"), msg="Hola duck typing!") # usa Protocol