代码如下:
# -*- 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