Python进阶之抽象类

【一】什么是抽象类

  • 与java一样,python也有抽象类的概念但是同样需要借助模块实现,抽象类是一个特殊的类,它的特殊之处在于只能被继承,不能被实例化

【二】为什么要有抽象类

  • 如果说类是从一堆对象中抽取相同的内容而来的,那么抽象类就是从一堆类中抽取相同的内容而来的,内容包括数据属性和函数属性

  • 从实现角度来看,抽象类与普通类的不同之处在于:抽象类中只能有抽象方法(没有实现功能),该类不能被实例化,只能被继承,且子类必须实现抽象方法。这一点与接口有点类似,但其实是不同的,即将揭晓答案

【三】抽象类的实现

  • 利用abc模块实现抽象类
# 【1】不重写抽象类方法
import abc


class Animal(metaclass=abc.ABCMeta):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @abc.abstractmethod
    def run(self):
        print(F'{self.name}可以到处跑!')


class Dog(Animal):
    def __init__(self, name, age):
        super().__init__(name, age)


# 子类不重写父类的方法就会报错
dog = Dog('小七', 2)
dog.run()
# Can't instantiate abstract class Dog with abstract method run

#【2】重写抽象类方法
import abc


class Animal(metaclass=abc.ABCMeta):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @abc.abstractmethod
    def run(self):
        print(F'{self.name}可以到处跑!')


class Dog(Animal):
    def __init__(self, name, age):
        super().__init__(name, age)

    # 在子类中重写父类的方法
    def run(self):
        print(F'{self.name}可以到处跑!')


dog = Dog('小七', 2)
dog.run()
# 小七可以到处跑!

【四】示例

import os
import abc
import json


class FileCheck(metaclass=abc.ABCMeta):
    def __init__(self):
        self.BASE_DIR = os.path.dirname(__file__)
        self.encoding = 'utf-8'

    @abc.abstractmethod
    def read_data(self):
        print('读取数据方法')

    @abc.abstractmethod
    def save_data(self):
        print('保存数据方法')


# 文本文件处理类
class TextFileCheck(FileCheck):
    def __init__(self):
        super().__init__()
        self.file_path = os.path.join(self.BASE_DIR, 'data.text')

    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_text = TextFileCheck()
print(obj_text.read_data())


# json文件处理类
class JsonFileCheck(FileCheck):
    def __init__(self):
        super().__init__()
        self.__ensure_ascii = False
        self.file_path = os.path.join(self.BASE_DIR, 'data.json')

    def read_data(self):
        with open(file=self.file_path, mode='r', encoding=self.encoding) as fp:
            data = json.load(fp=fp)
        return data

    def save_data(self):
        with open(file=self.file_path, mode='w', encoding=self.encoding) as fp:
            json.dump(obj={'username': "dream"}, fp=fp, ensure_ascii=self.__ensure_ascii)


json_obj = JsonFileCheck()
print(json_obj.read_data())
posted @ 2024-05-10 16:35  Ligo6  阅读(620)  评论(0)    收藏  举报