python繼承和多態

繼承:  python

  能夠吧父類的方法直接拿過來用就行,不須要在從新寫一遍方法。節省了代碼量。this

#!/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.pyspa

  this class Acode

  this class Ablog

固然你也也能夠重寫 該方法繼承

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

多態:utf-8

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

由此看來 子類的類型是基類的類型.class

可是基類的類型不是子類的類型。test

相關文章
相關標籤/搜索