python - python中的super()方法 (代码详解)

代码如下:

# -*- coding: utf-8 -*-


# 单继承
class hello(object):
    def print_c(self):
        print "hello world!"


class child(hello):
    def print_c(self):
        hello().print_c()


class child2(hello):
    def print_c(self):
        super(child2, self).print_c()
# 单继承


# 多继承
class A(object):
    def __init__(self):
        self.n = 10

    def minus(self, m):
        print '--- a'
        self.n -= m
        print '--- a1'


class B(A):
    def __init__(self):
        self.n = 7

    def minus(self, m):
        print '--- b'
        super(B, self).minus(m)
        self.n -= 2
        print '--- b1'


class C(A):
    def __init__(self):
        self.n = 12

    def minus(self, m):
        print '--- c'
        super(C, self).minus(m)
        self.n -= 5
        print '--- c1'


class D(B, C):
    def __init__(self):
        self.n = 15

    def minus(self, m):
        print '--- d'
        super(D, self).minus(m)
        self.n -= 2
        print '--- d1'

# 多继承


if __name__ == "__main__":
    # 单继承
    # hello类调用自己的方法
    hello().print_c()

    # child类中print_c方法中创建了hello对象并调用了hell类的print_c方法(子类中调用父类的方法)
    child().print_c()

    # super方法调用父类的print_c方法
    child2().print_c()

    # 多继承
    # b调用本身的minus方法,在minus方法中调用了父类的minus方法然后又执行了减2操作
    # 现在是B实例,所以传递的self.n = 7
    b = B()
    b.minus(2)
    print '--- b.n = ', b.n

    # 先看看它是怎样运行的,运行顺序
    print D.__mro__

    # 执行顺序:15-2-5-2-2=4
    d = D()
    d.minus(2)
    print '--- b.n ', d.n

输出结果:

hello world!
hello world!
hello world!
--- b
--- a
--- a1
--- b1
--- b.n =  3
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
--- d
--- b
--- c
--- a
--- a1
--- c1
--- b1
--- d1
--- b.n  4

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值