在我的项目中,我首先创建一个基类对象,但在程序中,它应该成为一个子类。在这个例子中,首先我创建了一个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
上面,我想继续使用已经创建为animal
的X
对象,并用X调用tranform_to_dog
方法,这样我就可以得到类似于z
的子类对象
尽管如此,变量仍然有一个硬映射,但可以用
@classmethod
来解决:相关问题 更多 >
编程相关推荐