类的继承与多态

2022-12-23 Python进阶

python中继承的概念和Java相同,特性也类似。在面向对象的程序设计中,定义一个新的 class 的时候,可以从某个现有的 class 继承,新的 class 称为子类,而被继承的 class 称为基类、父类或超类。

# 继承的定义与使用

先定义父类

# 默认继承自object类
class Animal(object):
    name = None  # 动物的名字

    def call(self):
        print('动物都会叫')

子类继承父类的变量和方法,使得子类具有父类的变量和方法,从而实现代码重用;同时,子类可以增加自己特有的方法。再来定义继承自Animal的子类

# 继承自Animal类
class Cat(Animal):
    name = '猫'
    def call(self):
        print('喵喵喵~~')


class Dog(Animal):
    name = '狗'

运行测试代码

cat = Cat()
cat.call()     # 喵喵喵~~

dog = Dog()
dog.call()     # 动物都会叫

# 类的多态

什么是多态?拿上述代码举例,call函数在Cat类和Dog类的表现形式是不一样的,也就是说同一个功能,表现出了多状态化,叫做多态。

# super的用法

super可以调用父类的方法或变量。

class Animal(object):
    name = '动物'
    def call(self):
        print('动物都会叫')

super的使用方法如下所示,需要super(当前类,self)调用

class Cat(Animal):
    name = '猫'

    def call(self):
        super(Cat, self).call()        
        print('喵喵喵~~')
        return super(Cat, self).name

# 类的多重继承

多继承语法如下

class Father:
    pass

class Mother:
    pass

class Child(Father, Mother):
    pass

# 多继承案例

先来定义两个父类

class Father:
    def __init__(self, father_attr):
        self.father_attr = father_attr

    def father_method(self):
        print('father_attr =', self.father_attr)
class Mother:
    def __init__(self, mother_attr):
        self.mother_attr = mother_attr

    def mother_method(self):
        print('mother_attr =', self.mother_attr)

再来定义多继承的子类

class Child(Father, Mother):
    def __init__(self, father_attr, mother_attr, child_attr):
        Father.__init__(self, father_attr)
        Mother.__init__(self, mother_attr)
        self.child_attr = child_attr

    def child_method(self):
        print('child_attr =', self.child_attr)     

测试代码

child = Child('Father', 'Mother', 'Child')        
child.father_method()
child.mother_method()
child.child_method()
上次更新: 1 年前