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__()

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