python inheritance polymorphism

Inheritance of python

 
 
#-*- coding:utf-8 -*- 
class A(object):
def __init__(self):
print('A: I will definitely execute!!')

def fun(self):
print('AAAA' )

def fun_A(self):
print('This is A alone!!')
pass

class B(object):
def __init__(self):
print('B: I will definitely execute it!!')

def fun (self):
print('BBBB')
pass

class C(A,B):
def __init__(self):
super(C, self).__init__()
super(A, self).__init__()
# super(). __init__()#python3 above syntax
print('C: I will definitely execute!!')

def fun(self):
super(C, self).fun()
super(A, self).fun()
# super().fun()# python3 and above syntax
print('CCCC')
pass

class D(B,A):
def __init__(self):
super(D,self).__init__()
super(B, self). __init__()
# super().__init__()# python3 syntax above
print('D: I will definitely execute!!')

def fun(self):
super(D, self).fun()
super(B, self).fun()
# super().fun()# python3 and above syntax
print('DDDD')
pass

f1=C()
print(C.__mro__)#Show inheritance order, from child to parent
f1.fun()
f1.fun_A()
print('----------------------------')
f2=D()
print(D.__mro__)#display Inheritance order, from child to parent
f2.fun()
f2.fun_A()
output:

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!!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325167196&siteId=291194637