Как преобразовать объект базового класса в объект подкласса? - PullRequest
0 голосов
/ 28 сентября 2019

В моем проекте я сначала создаю объект base_class, но позже в программе он должен стать подклассом.В этом примере сначала я создал animal, затем решил, что он должен стать dog.В этом случае я не хочу удалять свой старый объект animal и создавать новый объект dog, в котором может быть функция super(), потому что я не хочу передавать все аргументы создания animal заново.

Итак, есть ли какой-либо лучший способ, кроме показанного в примере, для кодирования чего-то подобного.

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

Выше я хочу продолжить работу с X объектом, который уже создан какanimal и вызов tranform_to_dog метода с X, чтобы я мог получить z как подклассный объект

1 Ответ

0 голосов
/ 28 сентября 2019

Тем не менее, существует жесткое сопоставление для переменных, но может быть решено с помощью @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 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...