Python3单继承与多继承

单继承

写法1(Python3+):

class Base():
    def __init__(self, a):
        self.a = a
        print("Base init'ed")

class ChildA(Base):
    def __init__(self):
        print("ChildA init'ed")
        super().__init__(123)
        print(self.a)

写法2(Python2+, Python3+):

class Base():
    def __init__(self, a):
        self.a = a
        print("Base init'ed")

class ChildA(Base):
    def __init__(self):
        print("ChildA init'ed")
        super(ChildA, self).__init__(123)
        print(self.a)

写法3(Python2+, Python3+):

class Base():
    def __init__(self, a):
        self.a = a
        print("Base init'ed")

class ChildA(Base):
    def __init__(self):
        print("ChildA init'ed")
        Base.__init__(self, 123)
        print(self.a)

Output:

>>> ChildA()
ChildA init'ed
Base init'ed
123

多继承

写法1:

class First():
    def __init__(self):
        print('1')
        super().__init__()
        print("first")
        
class Second():
    def __init__(self):
        print('2')
        super().__init__()
        print("second")

class Third(First, Second):
    def __init__(self):
        super().__init__()
        print("third")

写法2:

class First():
    def __init__(self):
        print('1')
        super(First, self).__init__()
        print("first")
        
class Second():
    def __init__(self):
        print('2')
        super(Second, self).__init__()
        print("second")

class Third(First, Second):
    def __init__(self):
        super(Third, self).__init__()
        print("third")

写法3:

class First():
    def __init__(self):
        print('1')
        super(First, self).__init__()
        print("first")
        
class Second():
    def __init__(self):
        print('2')
        super(Second, self).__init__()
        print("second")

class Third(First, Second):
    def __init__(self):
        First.__init__(self)
        print("third")

Output:


>>> Third()
1
2
second
first
third

注意super方法的返回:

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.
The object-or-type determines the method resolution order to be searched. The search starts from the class right after the type.
For example, if mro of object-or-type is D -> B -> C -> A -> object and the value of type is B, then super() searches C -> A -> object.

所以如果First类中没有super方法则会导致输出为:

1
first
third

这是由于根据方法解析路径MRO,在搜索到First后就停止了。
查看MRO:

# 执行方法
>>> Third.mro()
(__main__.Third, __main__.First, __main__.Second, object)

# 获取属性
>>> Third.__mro__
(__main__.Third, __main__.First, __main__.Second, object)

参考:
https://docs.python.org/3/library/functions.html#super
https://www.cnblogs.com/crazyrunning/p/7095014.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值