I have two classes that for example purposes I'll call Entero
and Flotante
. I need a method for an object to change classes on its own, without the intervention of external code.
The desired result is illustrated by the following pseudo-code:
class Entero:
def __init__(self, valor: int):
self.valor = valor
def convertir_a_flotante(self):
self.valor = float(self.valor)
# Aqui cambiar la clase del objeto a Flotante.
class Flotante:
def __init__(self, valor: float):
self.valor = valor
def convertir_a_entero(self):
self.valor = int(self.valor)
# Aqui cambiar la clase del objeto a Entero.
a = Entero(1)
print(f"Type(a) = {type(a)}") => Type(a) = <class '__main__.Entero'>
a.convertir_a_flotante()
print(f"Type(a) = {type(a)}") => Type(a) = <class '__main__.Flotante'>
The idea is not to generate a new object, but to preserve the existing one, so that previous references to the object are still valid.
Edition
With CalumRakk's answer and Abulafia's comments, I made a second version to check that the mutated object is really of the new class, implementing the common method__str__
class Entero:
def __init__(self, valor: int):
self.valor = valor
def convertir_a_flotante(self):
self.valor = float(self.valor)
self.__class__=Flotante
def __str__(self):
return f"Entero {self.valor}"
class Flotante:
def __init__(self, valor: float):
self.valor = valor
def convertir_a_entero(self):
self.valor = int(self.valor)
self.__class__=Entero
def __str__(self):
return f"Flotante {self.valor}"
a = Entero(1)
print(a, type(a))
a.convertir_a_flotante()
print(a, type(a))
which produces:
Entero 1 <class '__main__.Entero'>
Flotante 1.0 <class '__main__.Flotante'>
Process finished with exit code 0
You can use the property
__class__
to define the type of the object.All the code would look like this: