抽象类
【一】什么是抽象
# 将某几个具体的生物,根据特征总结成一个类,逐层向上总结 # 唐老鸭 肉鸭 北京烤鸭 ---> 鸭子 # 北极熊 黑熊 --> 熊 # 猫 老虎 --> 猫科 # 鸭子 熊 猫科 --> 动物
【二】什么是继承
# 动物 ---> 熊 ---> 黑熊
class Animal(object): def speak(self):print(f"动物叫") def __init__(self, color, foot, hand):self.color = colorself.foot = footself.hand = hand class Blackbear(Animal):def __init__(self, color, foot, hand):super().__init__(color, foot, hand) bear = Blackbear('black', 2, 2) print(bear.color, bear.foot, bear.hand) bear.speak()
【三】抽象类
-
所有继承父类的子类都必须重写父类的某些方法,这个父类就叫抽象类
import abc class Animal(metaclass=abc.ABCMeta): def __init__(self, color, foot, hand):self.color = colorself.foot = footself.hand = hand def speak(self):print(f"动物叫") # 使用abc装饰完以后在子类中必须重写@abc.abstractmethoddef walk(self):pass class Blackbear(Animal):def __init__(self, color, foot, hand):super().__init__(color, foot, hand) # 使用abc装饰完以后在子类中必须重写def walk(self):pass bear = Blackbear('black', 2, 2) print(bear.color, bear.foot, bear.hand) bear.speak()
-
文件处理示例
import os import abc class FileCheck(metaclass=abc.ABCMeta):def __init__(self):self.BASE_DIR = os.path.dirname(__file__)self.encoding = 'utf-8' @abc.abstractmethoddef read_data(self):print(f"读取数据") @abc.abstractmethoddef save_data(self):print(f"保存数据") # 文本文件处理类 class TextFileCheck(FileCheck):def __init__(self):super().__init__()self.file_path = os.path.join(self.BASE_DIR, 'data.txt') # 读def read_data(self):with open(file=self.file_path, mode='r', encoding=self.encoding) as fp:data = fp.read()return data# 写保存def save_data(self):with open(file=self.file_path, mode='w', encoding=self.encoding) as fp:fp.write("天下无双") obj_txt = TextFileCheck() print(obj_txt.save_data()) print(obj_txt.read_data()) import json # json文件处理类 class JsonFileCheck(FileCheck):def __init__(self):super().__init__()self.__ensure_ascii = Falseself.file_path = os.path.join(self.BASE_DIR, 'data.json') # 读def read_data(self):with open(self.file_path, mode='r', encoding=self.encoding) as fp:data = json.load(fp=fp)return data# 写保存def save_data(self):with open(self.file_path, mode='w', encoding=self.encoding) as fp:json.dump(obj={'username': 'knight'}, fp=fp, ensure_ascii=self.__ensure_ascii) json_obj = JsonFileCheck() print(json_obj.save_data()) print(json_obj.read_data())