Python super初始化父类

https://blog.youkuaiyun.com/death_include/article/details/89201789

https://zhuanlan.zhihu.com/p/28340924

https://www.jianshu.com/p/d9de3fc047ee

http://www.hongweipeng.com/index.php/archives/1065/?utm_source=tuicool&utm_medium=referral

http://www.cppcns.com/jiaoben/python/155536.html

https://www.zky.name/article/67.html

http://capturesoul.com/archives/8594

https://msd.misuland.com/pd/2884250137616452844

Parent.init(self) 与 super(Child, self).init() 的区别是什么?

super 理解成父类也是理所当然,python里其实指的是 MRO 中的下一个类!

super其实干了这件事,看这个答案:

def super(cls, inst):
mro = inst.class.mro() # Always the most derived class
return mro[mro.index(cls) + 1]
MRO 全称 Method Resolution Order,它代表了类继承的顺序。

super 是用来解决多重继承问题的,假设B C D 都是直接继承class A

class E(B, C, D):
def init(self):
# code…
如果E类的构造函数使用 super(E, self).init() 时,A类的构造函数会被执行一次,而用另一种方法,A类的构造函数会被执行多次。

在 MRO 中,基类永远出现在派生类后面,如果有多个基类,基类的相对顺序保持不变。


super()可以避免重复调用

如果childA基础Base, childB继承childA和Base,如果childB需要调用Base的 init ()方法时,就会导致 init ()被执行两次:

class Base(object):
    def __init__(self):
        print 'Base create'
 class childA(Base):
    def __init__(self):
        print 'enter A '
        Base.__init__(self)        
        print 'leave A'
 
 class childB(childA, Base):
    def __init__(self):
        childA.__init__(self)
        Base.__init__(self)
 
b = childB()

Base的 init ()方法被执行了两次

enter A 
Base create
leave A
Base create

使用super()是可避免重复调用

class Base(object):
    def __init__(self):
        print 'Base create'
 class childA(Base):
    def __init__(self):
        print 'enter A '
        super(childA, self).__init__()       
        print 'leave A'
 
 class childB(childA, Base):
    def __init__(self):
        super(childB, self).__init__()
 
b = childB()
print b.__class__.mro()
enter A 
Base create
leave A
[<class '__main__.childB'>, <class '__main__.childA'>, <class '__main__.Base'>, <type 'object'>]
<think>好的,我现在要回答用户的问题,关于如何在Python中使用super初始化父类。首先,我需要回忆一下相关的知识,并结合提供的引用内容来组织答案。 用户的问题是想了解使用super方法初始化父类的教程,所以需要详细讲解super的使用方法,特别是Python 2和Python 3的区别,以及不同的初始化方式之间的差异。根据提供的引用,比如引用[1]提到Python 2和3在super使用上的不同,还有引用[4]中提到的Parent.__init__(self)和super(Child, self).__init__()的区别,这些都需要涵盖进去。 首先,我应该介绍传统的父类初始化方法,即直接调用父类的__init__方法,并指出这种方法的缺点,比如需要显式传递self,并且在多重继承时可能重复调用父类。然后,再引入super函数,解释它在Python 3中的简化用法,以及Python 2中的旧语法。需要强调super在解决多重继承问题上的优势,比如方法解析顺序(MRO)的正确处理。 接下来,应该举一些代码示例,对比两种方法的不同。例如,先展示使用Parent.__init__(self)的例子,再展示使用super()的例子,并说明两者的区别。同时,要提到在多重继承的情况下,使用super能保证每个父类只被初始化一次,而传统方法可能导致多次调用或遗漏。 然后,需要讨论注意事项,比如在Python 2中使用super时需要显式传递类和实例参数,而在Python 3中可以省略。还要提到当父类改变时,使用传统方法需要修改所有子类的调用,而super则不需要,这提高了代码的可维护性。 此外,根据引用[5]中的例子,可以展示一个多重继承中使用super的正确方式,说明MRO如何工作,以及如何避免常见的错误。比如,GoodWay3类同时继承两个父类,通过super正确地初始化每个父类的方法。 最后,总结使用super的最佳实践,推荐在Python 3中使用super(),并解释为什么这样做更优。同时,回答用户可能的相关问题,比如如何处理不同参数的情况,或者在多重继承中的陷阱。 在整理这些内容时,需要确保结构清晰,分步骤讲解,让用户能够逐步理解。同时,引用相关的参考资料,如引用[2]提到的《Effective Python》中的建议,来增强回答的权威性。还要注意使用正确的中文表达,避免技术术语错误,并保持语句通顺自然。</think>### Python中使用super初始化父类的方法教程 #### 1. **传统初始化方式的问题** 在子类中直接通过父类名称调用`__init__`方法: ```python class Parent: def __init__(self, value): self.value = value class Child(Parent): def __init__(self, value): Parent.__init__(self, value) # 显式调用父类初始化方法 ``` - **缺点**: - 需要手动传递`self`参数。 - 在多重继承时,可能导致父类被多次初始化[^4]。 --- #### 2. **使用super的正确方式** **Python 3简化语法**: ```python class Child(Parent): def __init__(self, value): super().__init__(value) # 自动传递当前类和self ``` - **优点**: - 自动处理继承链,避免重复初始化。 - 支持动态方法解析(MRO),适用于多重继承[^2]。 **Python 2的旧语法**: ```python class Child(Parent): def __init__(self, value): super(Child, self).__init__(value) # 显式指定类和实例 ``` --- #### 3. **多重继承场景示例** ```python class A: def __init__(self): print("A initialized") class B(A): def __init__(self): super().__init__() print("B initialized") class C(A): def __init__(self): super().__init__() print("C initialized") class D(B, C): def __init__(self): super().__init__() print("D initialized") d = D() # 输出顺序遵循MRO:A -> C -> B -> D ``` - **MRO顺序**:通过`D.__mro__`可查看继承顺序`(D, B, C, A, object)`[^5]。 --- #### 4. **注意事项** - **参数传递**:若父类构造函数有参数,需在`super()`中正确传递。 - **Python 2兼容性**:需显式指定类和实例,如`super(Child, self).__init__(value)`[^1]。 - **避免混用**:不要同时使用`super()`和`Parent.__init__()`,否则可能导致父类重复初始化。 --- #### 5. **最佳实践总结** - **优先使用`super()`**:尤其在Python 3中,简化代码且避免继承问题。 - **统一风格**:项目中所有父类初始化保持一致性。 - **理解MRO**:在多重继承中,明确方法解析顺序[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值