Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python3.xOOP,对象定义后的继承_Python 3.x_Oop_Inheritance - Fatal编程技术网

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