0

In my project, I'm creating a base_class object first, but later on the program it should become a subclass. In the example, first I created an animal, later I've decided that it should become a dog. In this case, I don't wanna delete my old animal object and create a new dog object which may have super() function in it, because I don't want to pass all animal creation arguments all over again.

So is there any better method other than shown in the example to code something like this.

class animal:
    def __init__(self, H):
        self.hight =  H
        print("animal created @ height : ", self.hight)

x = animal(10)
#animal created @ height :  10

class dog: #with cheap trick
    def __init__(self, animal_object,  color):
        self.animal_object = animal_object
        self.color = color
        print("animal became a dog")
        print("dog's @ color : ", self.color)
        print("dog's @ heigth : ", self.animal_object.hight)

y = dog(x, "black") #animal becomes a dog

# animal became a dog
# dog's @ color :  black
# dog's @ heigth :  10


class tranform_to_dog(animal): #super() method
    def __init__(self, H, color):
        super().__init__(H)
        self.color = color
        print("Dog created as a subclass of animal, heigth: {}, color:{}".format(self.hight,self.color))

z = tranform_to_dog(8, "white")
#Dog created as a subclass of animal, heigth: 8, color:white

Above, I want to keep going with X object which is already created as an animal and call tranform_to_dog method with X so I can get z like subclassed object

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Possible duplicate of [Cast base class to derived class python (or more pythonic way of extending classes)](https://stackoverflow.com/questions/3464061/cast-base-class-to-derived-class-python-or-more-pythonic-way-of-extending-class) – yukashima huksay Sep 28 '19 at 14:43
  • But, `x.__class__ =tranform_to_dog` does not run `tranform_to_dog` 's `__init__` function. Skipping this may cause a dog with no fur!! – Emir Atakan Yılmaz Sep 28 '19 at 15:01

1 Answers1

0

Still, there is a hard mapping for variables but might be solved with @classmethod :

class animal:
    def __init__(self, H):
        self.hight =  H
        print("animal created @ height : ", self.hight)

x = animal(10)
#animal created @ height :  10

class tranform_to_dog(animal): #super() method
    def __init__(self, H, color):
        super().__init__(H)
        self.color = color
        print("Dog created as a subclass of animal, heigth: {}, color:{}".format(self.hight,self.color))

    @classmethod
    def from_animal(cls, animal_object, color):
        return cls(animal_object.hight, color)


w = tranform_to_dog.from_animal(x, "yellow")
#Dog created as a subclass of animal, heigth: 10, color:yellow