Python 是否可以从子类uu init_uuu()中初始化父类?

Python 是否可以从子类uu init_uuu()中初始化父类?,python,inheritance,subclass,Python,Inheritance,Subclass,从子类内部初始化父类,以便父类属性可用于创建的子类实例,这是一种良好的做法吗? 这样做是否有替代方案或最佳做法 例如: class Animal(object): def __init__(self, name, weight, cute=False, image=None): #Instantiation attributes self.name = name self.weight = weight self.cute

从子类内部初始化父类,以便父类属性可用于创建的子类实例,这是一种良好的做法吗? 这样做是否有替代方案或最佳做法

例如:

class Animal(object):
    def __init__(self, name, weight, cute=False, image=None):
        #Instantiation attributes
        self.name = name
        self.weight = weight
        self.cute = cute
        self.image = image
        #Attributes common to all animals
        self.extinct = False
    def get_animal_stats(self):
        print arbitrary_animal_stat

class Dog(Animal):
    def __init__(self, name, weight):
        Animal.__init__(self, name, weight, cute=True, image="dog.com")
        #Additional attributes unique to dogs
        self.number_legs = 4
        self.teeth = True
    def make_noise(self):
        print "Bark!"
据我所知,在子类初始化期间,没有初始化父类,子类对象只能访问自己的属性(即number_legs和tooth,make_noise),而不能访问父类的属性或方法(即execute和get_animal_stats)

我发现自己为预定义对象编写了许多小类,但必须用子对象初始化父对象。通过这种方式,我可以创建一个简单的动态动物,或者通过Dog子类创建一个更具描述性的动物


从子类实例访问父属性和方法的正确方法是什么?我是否误解了子类的用法?

这没什么错,尽管您可能希望使用super()

或者在Python 3中:

super().__init__...

它不仅是可以接受的,而且几乎应该始终调用父类的构造函数。你不这么做的唯一原因是

  • 绝对确保在父类中永远不会定义任何初始化代码,这是对象正常运行所必需的
  • 您希望显式重写父类的初始化行为
  • 对于新样式的类(从对象继承的类),最好使用
    super()
    ,因为它在多重继承的情况下会考虑解析顺序。在Python 2.7中,使用:

    class ParentFooA(GrandparentFoo):
        def __init__(self):
            some_important_initialization_code()
    
    class ChildFoo(ParentFoo):
        def __init__(self):
            super(ChildFoo, self).__init__()
    
    请注意,另一个很好的属性是,您不必在
    ChildFoo
    中的任何位置使用名称
    ParentFoo
    ,定义继承时除外(例如,在
    类ChildFoo(…)
    行中)。它也适用于其他方法:

    class ChildFoo(ParentFoo):
        ...
        def do_buzz(self):
            super(ChildFoo, self).do_buzz()
    
    super()
    不适用于旧式类(即不从
    对象继承的类)。
    这意味着对于大多数标准库,您仍然需要显式调用父类的构造函数。因此,在这种情况下:

    class OldStyleParent:
        def __init__(self):
            ...
    
    您必须在
    中显式地调用
    OldStyleParent.\uuuu init\uuuu()

    在Python 3中,
    super
    的语法很简单:

    class ChildFooInPython3(ParentFoo):
        def __init__(self):
            super().__init__()
    

    回答得好!我有几个澄清的问题:你什么时候会选择1。?如果您确定父类中没有子类运行所需的初始化代码,那么应该首先对子类进行子类化吗?Super()很好了解。从您的回答中,我理解它是用于多重继承的,但是明确说明您实例化的父类(关于继承堆栈)不是更好吗?
    super()
    自动适应继承结构中的更改,允许您编写子类而不必(过多)有关其父类的知识。在Python中,继承堆栈不需要是线性的,
    super()
    (正确且一致地使用时)有助于消除多重继承的情况。这些“混合插件”主要由staticmethods组成,实际上不需要任何初始化。我还使用抽象基类来实施Java风格的“接口”。这些类的存在使得它们的方法将被重写,并且通常不需要任何初始化。
    class OldStyleParent:
        def __init__(self):
            ...
    
    class ChildFooInPython3(ParentFoo):
        def __init__(self):
            super().__init__()