python之7-2類的繼承與多態

  • 類的繼承的意思就如同父子關係同樣,這個兒子繼承了父親的一切,可是在某些地方(屬性)相同的時候,兒子的屬性大於老子的屬性(覆蓋),最底層類,總會繼承最接近它的那個類的屬性initpython

  • 類的多態老是和繼承相連的,沒有繼承,就沒有多態一說.一個子類的實例,它即屬於這個子類,也屬於父類,好比:父親A和兒子B,兒子B即屬於兒子類,也屬於人類,可是它不屬於父親類函數

  • 多態是面嚮對象語言的一個基本特性,多態意味着變量並不知道引用的對象是什麼,根據引用對象的不一樣表現不一樣的行爲方式。在處理多態對象時,只須要關注它的接口便可spa

  • 多態的實際用法是構建一個類外函數 ,函數的參數爲指向類對象的變量,而後函數體返回這個變量(類對象)的方法。這樣子,調用函數就能夠根據實例類型,來返回對應的方法。code

  • 例以下面這個例子:對象

#!/usr/bin/env python

# coding=utf-8

#定義一個父類人類

class humen(object):

    def __init__(self,name,eye=2,age=None):

        self.name = name

        self.eye = eye

        self.age = age

    def action(self):

        print "%s%u個eye,這我的已經有%u歲了" %(self.name,self.eye,self.age)



class father(humen):

    def action(self):

        print "我是%s,是一名父親" %self.name

class son(father):

    def action(self):

        print "我是%s,是一名的兒子" %self.name

one = humen("one",2,20)

tom = father('tom')

david = son('david')

def actiont(hm):

    return hm.action()

actiont(one)

actiont(tom)

actiont(david)

aaa103439@aaa103439-pc:~/桌面/python$ python test7_類_多態.py 

one有2個eye,這我的已經有20歲了

我是tom,是一名父親

我是david,是一名的兒子
  • 若是想要實如今兒子實例中輸出父親實例的屬性,則能夠作以下修改:
#!/usr/bin/env python

# coding=utf-8

#定義一個父類人類

class humen(object):

    def __init__(self,name,eye=2,age=None):

        self.name = name

        self.eye = eye

        self.age = age

    def action(self):

        print "%s%u個eye,這我的已經有%u歲了" %(self.name,self.eye,self.age)



class father(humen):

    namef = []

    def __init__(self,name):

        self.name = name

        father.namef = name

    def action(self):

        print "我是%s,是一名父親" %self.name

class son(humen):

    def action(self):

        print "我是%s,是%s的兒子" %(self.name,father.namef)

one = humen("one",2,20)

tom = father('tom')

david = son('david')

bob = father('bob')

micheal = son('micheal')

def actiont(hm):

    return hm.action()

actiont(one)

actiont(tom)

actiont(david)

actiont(bob)

actiont(micheal)

aaa103439@aaa103439-pc:~/桌面/python$ python test7_類_多態.py 

one有2個eye,這我的已經有20歲了

我是tom,是一名父親

我是david,是bob的兒子

我是bob,是一名父親

我是micheal,是bob的兒子
  • 註釋:這裏將son的父類替換爲了human,目的就是在son類實例調用的父類的時候,避免了father類中列表namef的最後一個元素追加進son類實例的元素
相關文章
相關標籤/搜索