Python 3.x Python3.xOOP,对象定义后的继承
这是代码Python 3.x Python3.xOOP,对象定义后的继承,python-3.x,oop,inheritance,Python 3.x,Oop,Inheritance,这是代码 class Animal(object): def __init__(self): self.alive = "alive" self.good = "good" self.eyecolor = "varys" sally = Animal() sally.eyecolor = "brown" class Canine(Animal): def __init__(self): super(Canine,self).__init__
class Animal(object):
def __init__(self):
self.alive = "alive"
self.good = "good"
self.eyecolor = "varys"
sally = Animal()
sally.eyecolor = "brown"
class Canine(Animal):
def __init__(self):
super(Canine,self).__init__()
self.legs = 4
self.fur = "everywhere"
sally = Canine()
print(sally.eyecolor)
所以在这个场景中,我有一个类和一个由它构造的对象,sally。现在我有了一个新的班级,我想搬到萨莉那里。有没有办法让萨莉进入犬类课程,这样她就可以保持原来的眼睛颜色
- 我知道我可以再做一次sally.eyecolor=“brown”,但是,在实际问题中,我有更多的属性,并且为每个属性做这些都很麻烦
- 我在考虑copy.deepcopy(sally),但我不确定接下来如何让她通过类实例继承新类
candie.from\u animal
你可能会考虑这样做,因为从一种类型到另一种类型的铸造是常见的。举个例子,你可能在过去做过这件事
x = float(1) # 1.0
那你为什么不能这么做呢
canine = Canine(some_animal)
答案是Python不仅仅是推断如何将一个类转换为另一个类,即使它是一个子类。这种行为必须通过某种方法来定义
例如,如果要将类对象强制转换为浮点
,则必须定义\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
特殊方法
由此得出的自然结论是,您需要实现自己的类方法来从动物类型的对象中获取犬科类型的对象
class Canine(Animal):
...
@classmethod
def from_animal(cls, animal):
canine = cls()
canine.eyecolor = animal.eyecolor
# Implement any additional logic here
return canine
sally = Animal()
sally.eyecolor = "brown"
sally = Canine.from_animal(sally) # Sally knows where she stands now
请注意,没有任何东西可以阻止您在类动物中定义方法来定义犬科动物
class Animal(object):
...
def to_canine(self):
canine = Canine()
canine.eyecolor = self.eyecolor
return canine