Python继承

来源:互联网 发布:mac os 磁盘清理 编辑:程序博客网 时间:2024/04/30 12:04

继承

如果父类定义了__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:redApple's color:redGrow...fruit's color:yellowBanana's color:yellowbanana grow...

还可以使用super类的super()方法调用父类的__init__方法;

super()的声明如下:

super(type,obj) #type是某个类,obj是某个类的实例化对象 super()可以绑定type类的父亲

使用super()调用父类

class Fruit():    def __init__(self):        print("Parent")class Apple(Fruit):    def __init__(self):        super(Apple,self).__init__()        #使用super()调用父类更直观        print("child")if __name__ == "__main__":    Apple()

输出结果:

Parentchild

抽象基类

抽象基类是对一类是我的特征行为的抽象,由抽象方法组成;
在python3中可以使用abc模块,抽象基类不能被直接实例化;
例子:
from abc import ABCMeta,abstractmethod  #导入模块class Fruit(metaclass = ABCMeta): #抽象类    @abstractmethod #使用@abstractmethod定义抽象函数    def grow(slef):        passclass Apple(Fruit):    def grow(self): #子类中必须重写抽象函数        print("Apple grow...")if __name__ == "__main__":    apple = Apple()    apple.grow()    fruit = Fruit()  #抛出异常输出结果:Apple grow...Traceback (most recent call last):  File "C:\Users\cs\Desktop\hello.py", line 15, in <module>    fruit = Fruit()TypeError: Can't instantiate abstract class Fruit with abstract methods grow

多态

子类可以替代父类对象
class Fruit:    def __init__(self,color = None):        self.color = colorclass 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): #判断参数fruit的类型            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)    shop.sellFruit(banana)输出结果:sell Applesell Fruitsell Bananasell Fruit

多重继承

多重继承语法:
class_name(parent_class1,parent_class2)
例子:
watermelon只会调用第一个被继承类的__init__.
class Fruit:    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):    passif __name__ == "__main__":    w = Watermelon()    w.grow()    w.plant()输出结果:initialize Vegetablegrow...plant...

Mixin机制

class Fruit(): #基类    def __init__(self):        passclass HuskedFruit(Fruit): #削皮水果    def __init__(self):        print("initalize HuskedFruit")    def husk(self):        print("husk...")class DecorticatedFruit(Fruit): #剥皮水果    def __init__(self):        print("initalize DecorticatedFruit")    def decorticat(self):        print("decorticat...")class Apple(HuskedFruit):    passclass Banana(DecorticatedFruit):    pass#下面mixin机制class Fruit(object): #基类    def __init__(self):        passclass HuskedFruit(object): #削皮水果    def __init__(self):        print("initalize HuskedFruit")    def husk(self):        print("husk...")class DecorticatedFruit(object):    def __init__(self):        print("initalize DecorticatedFruit")    def decorticat(self):        print("decorticat...")class Apple(HuskedFruit,Fruit):    passclass Banana(DecorticatedFruit,Fruit):    pass#Mixin减少了继承的层次,把依赖关系移动到了分类层,如果要进行新的分类只要在#第二层中添加新的类型,然后在多重继承中添加新的类



0 0
原创粉丝点击