Python网络爬虫技术与实战
上QQ阅读APP看书,第一时间看更新

1.9.4 多态性

继承机制说明子类具有父类的公有属性和方法,而且子类可以扩展自身的功能,添加新的属性和方法。因此,子类可以替代父类对象,这种特性称为多态性。Python的动态类型决定了Python的多态性。下面展示多态性的代码。


# -*- coding:utf-8 -*-

# 类的创建
class Fruit(object):
    def __init__(self, color=None):               # __init__为类的构造函数
        self.color = color                        # 实例属性
 
class Apple(Fruit):                               # 继承自Fruit类
    def __init__(self, color='red'):              # 子类的构造函数
        Fruit.__init__(self, color)               # 显式调用父类的构造函数

class Banana(Fruit):                              # 继承自Fruit类
    def __init__(self, color='yellow'):           # 子类的构造函数
        Fruit.__init__(self, color)      # 显式调用父类的构造函数
    
class Fruitshop(object):
    def sellFruit(self, fruit):
        if isinstance(fruit, Apple):
            print "sell apple"
        if isinstance(fruit, Banana):
            print "sell apple"
        if isinstance(fruit, Fruit):
            print "sell Fruit"            
if __name__ == '__main__':
    shop = Fruitshop()
    apple = Apple()
    banana = Banana()
    shop.sellFruit(apple)
    shop.sellFruit(banana)

输出结果如下:


sell apple
sell Fruit
sell apple
sell Fruit

在Fruitshop类中定义了sellFruit()方法,该方法提供参数fruit。sellFruit()根据不同的水果类型返回不同的结果,实现了一种调用方式不同的执行结果;这就是多态。利用多态性,可以增加程序的灵活性和可扩展性。