如何将基类对象转换为子类对象?

2024-06-17 10:00:03 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的项目中,我首先创建一个基类对象,但在程序中,它应该成为一个子类。在这个例子中,首先我创建了一个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

上面,我想继续使用已经创建为animalX对象,并用X调用tranform_to_dog方法,这样我就可以得到类似于z的子类对象


Tags: 对象方法selfobjectinitdefclasscolor
1条回答
网友
1楼 · 发布于 2024-06-17 10:00:03

尽管如此,变量仍然有一个硬映射,但可以用@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 

相关问题 更多 >