# -*- encoding: utf-8 -*-
"""
@日期 : 2024/5/20 下午11:36
@作者 : 张秋平
@邮箱 : 1324616745@qq.com
@文件 : abstract_test.py
@描述 : 测试 python 中的抽象类及抽象方法
"""
from abc import ABC, abstractmethod
# 通过继承 abc.ABC 来定义一个抽象基类, 该类无法被直接实例化为对象
class People(ABC):
def __init__(self, name: str, age: int):
self.name = name
self.age = age
# 这里定义了一个抽象方法, 这个方法没有默认实现, 需要子类去实现
# 虽然也可以在这里指定该抽象函数期望的返回值类型, 但实际在运行时, python 并不会检查子类中该函数实现的返回值类型与此是否匹配
@abstractmethod
def say_hello(self):
pass
class Student(People):
def __init__(self, name: str, age: int, score: int):
super().__init__(name, age)
self.score = score
def say_hello(self):
print(f'我是 {self.name}, 今年 {self.age} 岁, 成绩是 {self.score}')
class Teacher(People):
def __init__(self, name: str, age: int, salary: int):
super().__init__(name, age)
self.salary = salary
def say_hello(self):
print(f'我是 {self.name}, 今年 {self.age} 岁, 工资是 {self.salary}')
s1 = Student('张三', 18, 100)
t1 = Teacher('李四', 30, 10000)
def hello(people: People):
people.say_hello()
hello(s1)
hello(t1)
""" 输出:
我是 张三, 今年 18 岁, 成绩是 100
我是 李四, 今年 30 岁, 工资是 10000
"""
版权归属:
张秋平
许可协议:
本文使用《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》协议授权
评论区