python知識撿拾---方法、繼承、多態

方法的動態特性:
class_name.method_name = function_name
實例:
class Fruit:
    pass

def add(self): #定義函數add()
    print "grow..."

if __name__=="__main__":
    Fruit.grow = add  #把函數add()添加到Fruit類中,方法名爲grow
    fruit=Fruit()
    fruit.grow()   #輸出結果:grow...

利用python的動態特性,還可以對已經定義的方法進行修改,修改方法的語法格式如下所示:

class_name.method_name=function_name
實例:
class Fruit:
    def grow(self):
        print "grow..."

def update(): #定義函數add()
    print "update..."

if __name__=="__main__":
    fruit = Fruit()  #把函數add()添加到Fruit類中,方法名爲grow

    fruit.grow()   #輸出結果:grow...
    fruit.grow = update
    fruit.grow()
#輸出結果爲:
grow...
update...
繼承:python在類名後使用一對括號表示繼承的關係,括號中的類即爲父類。

如果父類定義了__init__方法,子類必須顯示調用父類的__init__方法,如果子類需要擴展父類的行爲,可以添加__init__方法的參數
實例:

class Fruit:
    def __init__(self,color):
        self.color=color
        print "fruit's color: % s" % self.color

    def grow(self):
        print "grow..."

class Apple(Fruit):
    def __init__(self,color):
        Fruit.__init__(self,color)
        print "apple's color:% s" % self.color

class Banana(Fruit):
    def __init__(self,color):
        Fruit.__init__(self,color)
        print "banana's color:% s" %self.color

    def grow(self):
        print "banana grow..."

if __name__=='__main__':
    apple = Apple("red")
    apple.grow()
    banana = Banana("yellow")
    banana.grow()
結果爲:
fruit's color: red
apple's color:red
grow...
fruit's color: yellow
banana's color:yellow
banana grow...
還可以使用super類的super()調用父類的__init__方法

實例:

class Fruit(object):
    def __init__(self):
        print "parent"

class Apple(Fruit):
    def __init__(self):
        super(Apple,self).__init__()
        print "child"

if __name__=='__main__':
    Apple()
結果爲:
parent
child

注意:super類的實現代碼繼承了object,因此Fruit類必須繼承object。如果不繼承object,使用super()將出現錯誤。

抽象類的模擬

抽象類是對一類事物的特徵和行爲的抽象,抽象類由抽象方法組成,抽象類的特徵是不能被實例化
實例:

def abstract():     #定義全局函數abstract(),該函數拋出NotImplementedError異常
    raise NotImplementedError("abstract")

class Fruit:
    def __init__(self):
        if self.__class__ is Fruit:   #對實例化對象表示的類進行判斷,如果是Fruit類,則調用abstract()拋出異常
            abstract()
        print "Fruit"

class Apple(Fruit):
    def __init__(self):
        Fruit.__init__(self)
        print "Apple"

if __name__=="__main__":
    apple=Apple()
如果調用fruit=Fruit()程序將拋出如下異常信息:
NotImplementedError:abstract
多態性:

動態多態是指發出同樣的消息被不同類型的對象接收時,有可能導致完全不同的行爲。
實例:

class Fruit:
    def __init__(self,color=None):
        self.color=color

class Apple(Fruit):
    def __init__(self,color="red"):
        Fruit.__init__(self,color)

class Banana(Fruit):
    def __init__(self,color="yellow"):
        Fruit.__init__(self,color)

class FruitShop:
    def sellFruit(self,fruit):
        if isinstance(fruit,Apple):
            print "sell apple"
        if isinstance(fruit,Banana):
            print "sell banana"
        if isinstance(fruit,Fruit):
            print "sell fruit"

if __name__=="__main__":
    shop =FruitShop()
    apple = Apple("red")
    banana=Banana("yellow")
    # shop.sellFruit(apple)#結果sell apple  sell fruit
    shop.sellFruit(banana) #結果sell banana  sell fruit
多重繼承:python支持多重繼承,即一個類可以繼承多個父類

實例:

class Fruit(object):
    def __init__(self):
        print "initialize Fruit"

    def grow(self):
        print "grow..."

class Vegetable(object):
    def __init__(self):
        print "initialize Vegetable"

    def plant(self):
        print "plant..."

class Watermelon(Vegetable,Fruit):
    pass

if __name__=="__main__":
    w=Watermelon()
    w.grow()
    w.plant()
輸出結果:
initialize Vegetable
grow...
plant...

注意:由於Watermelon繼承了Vegetable,Fruit類,因此Watermelon將繼承__init__()。但是Watermelon只會調用第1個被繼承的類的__init__,即Vegetable類的__init__()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章