Skip to content

Instantly share code, notes, and snippets.

@j2deme
Created September 27, 2023 16:01
Show Gist options
  • Save j2deme/4c53cd7c56ab8075ee7fc38fa183968f to your computer and use it in GitHub Desktop.
Save j2deme/4c53cd7c56ab8075ee7fc38fa183968f to your computer and use it in GitHub Desktop.
Composición de Clases
# Composición por atributos
from motor import Motor
from llanta import Llanta
class Coche:
def __init__(self, no_serie):
self.motor = Motor(no_serie)
self.ruedas = [
Llanta("FI"), Llanta("FD"),
Llanta("TI"), Llanta("TD")
]
def encender(self):
self.motor.encender()
def inflarRuedas(self):
for llanta in self.ruedas:
llanta.inflar()
# Composición por métodos (paso de parámetros)
class Coche:
def __init__(self):
self.llantas = []
def encender(self, motor):
motor.encender()
def agregarLlanta(self, llanta):
self.llantas.append(llanta)
class Llanta:
def __init__(self, etiqueta):
self.etiqueta = etiqueta
self.presion = 0
def inflar(self, presion=32):
self.presion = presion
print(f"Inflando llanta a {self.presion} PSI")
def __str__(self):
return f"{self.etiqueta} ({self.presion} PSI)"
from motor import Motor
from llanta import Llanta
from cochem import Coche as CocheMetodos
from cochea import Coche as CocheAtributos
# Se utiliza "as ..." para evitar colisión en los nombres de clases
def main():
ejemploCocheMetodos()
ejemploCocheAtributos()
def ejemploCocheMetodos():
print("Composición por Métodos")
motor = Motor("4569")
coche = CocheMetodos()
coche.encender(motor)
fi = Llanta("Frontal Izq")
fi.inflar(28)
fd = Llanta("Frontal Der")
fd.inflar(28)
coche.agregarLlanta(fi)
coche.agregarLlanta(fd)
print(coche.llantas[0])
def ejemploCocheAtributos():
print("Composición por atributos")
coche = CocheAtributos("ABCDE")
coche.encender()
coche.inflarRuedas()
print(coche.ruedas[2])
if __name__ == "__main__":
main()
class Motor:
def __init__(self, no_serie):
self.no_serie = no_serie
def encender(self):
print("Encendiendo motor")
def __str__(self):
return f"Motor: {self.no_serie}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment