类的抽象类和归一化

首先抽象类是一个特殊的类,它的特殊之处在于只能被继承,不能被实例化:

比如我们有香蕉的类,有苹果的类,有桃子的类,从这些类抽取相同的内容就是水果这个抽象的类,你吃水果时,要么是吃一个具体的香蕉,要么是吃一个具体的桃子……你永远无法吃到一个叫做水果的东西。抽象类一般是用来当做接口,为了实现某些相似的功能

1.什么是接口

  接口可以理解为自己给使用者来调用自己功能方法的入口。

2.为什么要用接口

(1).可以实现权限控制,比如可以通过接口做一下访问控制,可以允许或者拒绝调用者的一些操作。

(2).降低了使用者的使用难度,使用者只需要知道怎么调用即可,不需要知道里边的具体实现方法。

import abc
class Animal(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def run(self):
        pass
    @abc.abstractmethod
    def eat(self):
        pass

class People(Animal):
    def run(self):
        print('People is walking')

    def eat(self):
        print('People is eating ')


class People(Animal):
    def run(self):
        print('People is walking')

    # def eat(self):
    #     print('People is eating ')


class Pig(Animal):
    def run(self):
        print('Pig is walking')

    def eat(self):
        print('Pig is eating ')


class Dog(Animal):
    def run(self):
        print('Dog is walking')

    def eat(self):
        print('Dog is eating ')


peo1 = People()
pig1 = Pig()
dog1 = Dog()

分析总结:在上面的额代码中,Animal类就是抽象类,它是基于以下的三个类以及相似的功能而抽取相似形成的。抽象类是一个特殊的类,它的特殊之处在于只能被继承,不能被实例化:比如我们有香蕉的类,有苹果的类,有桃子的类,从这些类抽取相同的内容就是水果这个抽象的类,你吃水果时,要么是吃一个具体的香蕉,要么是吃一个具体的桃子……你永远无法吃到一个叫做水果的东西。同时为了当做接口使用,通过设定Animal类的meteclass以及对类的函数属性用装饰器修饰。继承了Animal的类中必须有这样的函数属性。而归一化的体显在于:不同的对象可以不用在意各自的方法时候交叉,因为它们的类中的函数属性是相同的。

原文地址:https://www.cnblogs.com/z18271397173/p/9130459.html