python 的继承
#-*- coding:utf-8 -*-
class A(object):
def __init__(self):
print('A:我是肯定会执行的!!')
def fun(self):
print('AAAA')
def fun_A(self):
print('这是A单独有的!!')
pass
class B(object):
def __init__(self):
print('B:我是肯定会执行的!!')
def fun(self):
print('BBBB')
pass
class C(A,B):
def __init__(self):
super(C, self).__init__()
super(A, self).__init__()
# super().__init__()#python3以上语法
print('C:我是肯定会执行的!!')
def fun(self):
super(C, self).fun()
super(A, self).fun()
# super().fun()#python3以上语法
print('CCCC')
pass
class D(B,A):
def __init__(self):
super(D,self).__init__()
super(B, self).__init__()
# super().__init__()#python3以上语法
print('D:我是肯定会执行的!!')
def fun(self):
super(D, self).fun()
super(B, self).fun()
# super().fun()#python3以上语法
print('DDDD')
pass
f1=C()
print(C.__mro__)#显示继承顺序,从子到父
f1.fun()
f1.fun_A()
print('---------------------------')
f2=D()
print(D.__mro__)#显示继承顺序,从子到父
f2.fun()
f2.fun_A()
输出:
A:我是肯定会执行的!!
B:我是肯定会执行的!!
C:我是肯定会执行的!!
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>)
AAAA
BBBB
CCCC
这是A单独有的!!
---------------------------
B:我是肯定会执行的!!
A:我是肯定会执行的!!
D:我是肯定会执行的!!
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.A'>, <type 'object'>)
BBBB
AAAA
DDDD
这是A单独有的!!
python 多态
#-*- coding:utf-8 -*-
class animal:
def run(self):
pass
class people(animal):
def run(self):
print('people is walking!!')
class pig(animal):
def run(self):
print('pig is walking!!')
class dog(animal):
def run(self):
print('dog is walking!!')
class fun(object):
def run(self,obj):
obj.run()
f=fun()#在这种情况下,由animal定义方法名,直接调用fun的方法,实现多态,统一接口
f.run(people())
f.run(pig())
f.run(dog())
输出:
people is walking!!
pig is walking!!
dog is walking!!