python继承和多态

继承:  

  可以吧父类的方法直接拿过来用就行,不需要在重新写一遍方法。节省了代码量。

#!/usr/bin/python
# -*-coding:utf-8-*-
"""
    继承
"""
class A(object):
    def run(self):
        print "this class A"
#这种方式就是继承。
class B(A):
    pass
class C(B):
    pass

test_b = B() #这里称test_b 是类B的类型
test_c = C() #同理。。。
test_b.run() 
test_c.run()

————--------看结果————————---

➜  Test python class1.py

  this class A

  this class A

当然你也也可以重写 该方法

#!/usr/bin/python
# -*-coding:utf-8-*-
"""
    多态
"""
class A(object):
    def run(self):
        print "this class A"
class B(A):
    def run(self):
        print "this class B"
class C(B):
    def run(self):
        print "this class C"

test_b = B() #这里称test_b 是类B的类型
test_c = C() #同理。。。
test_b.run() 
test_c.run()
-------------看结果———————————————— ➜ Test python class1.py this class B this class C

多态:

#!/usr/bin/python
# -*-coding:utf-8-*-
"""
    多态
"""
class A(object):
    def run(self):
        print "this class A"
class B(A):
    def run(self):
        print "this class B"
class C(B):
    def run(self):
        print "this class C"
test_a = A() #这里称test_a 是类A的类型
test_b = B() #这里称test_b 是类B的类型
test_c = C() #同理。。。

print isinstance(test_a,A)
print isinstance(test_b,B)
print isinstance(test_c,C)
print "------------检查子类的类型 是否是 基类的类型:------"
print isinstance(test_c,A)
print isinstance(test_b,A)
print "------------检查基类的类型 是否是 子类的类型:------"
print isinstance(test_a,C)
print isinstance(test_a,B)

--------------结果------------
True
True
True
➜  Test python class1.py
True
True
True
------------检查子类的类型 是否是 基类的类型:------
True
True
------------检查基类的类型 是否是 子类的类型:------
False
False

由此看来 子类的类型是基类的类型.

但是基类的类型不是子类的类型。

原文地址:https://www.cnblogs.com/yhl664123701/p/6048163.html