← 返回首页
Python3基础教程(三十四)
发表时间:2022-04-07 12:03:00
继承和多态

1.继承

python 同样支持类的继承,如果一种语言不支持继承,类就没有什么意义。子类的定义语法如下所示:

class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>

类似Java,如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法,实例如下:

# -*- coding: utf-8 -*-
# @Time : 2022/4/7 12:18
# @File : inherit.py
# @Software : PyCharm

class Animal(object):
    def eat(self):
        print('Animal is eating...')
        return


class Human(Animal):

    # 构造方法
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender

    def eat(self):
        print(self.name, " is eating....")


class Dog(Animal):
    def eat(self):
        print('Dog is eating bone now....')

# 定义动物吃饭的方法
def animal_eat(animal):
    # 这里有多态
    animal.eat()
    return


a = Animal()
a.eat()

p = Human('张三', 20)
p.eat()

dog = Dog()
dog.eat()

print(isinstance(p, Animal))
print(isinstance(p, Human))
print(isinstance(p, Dog))

animal_eat(dog)

运行结果:

Animal is eating...
张三  is eating....
Dog is eating bone now....
True
True
False
Dog is eating bone now....

2.类的专有方法

python有以下专有方法,通常不建议去重写这些专有方法。

__init__ : 构造函数,在生成对象时调用
__del__ : 析构函数,释放对象时使用
__repr__ : 打印,转换
__setitem__ : 按照索引赋值
__getitem__: 按照索引获取值
__len__: 获得长度
__cmp__: 比较运算
__call__: 函数调用
__add__: 加运算
__sub__: 减运算
__mul__: 乘运算
__truediv__: 除运算
__mod__: 求余运算
__pow__: 乘方