3.1.4 抽象类与归一化
抽象类的作用: 规范化子类,降低使用者的难度。
抽象类是父类,该类不实现自己的方法,子类必须实现抽象类所有的方法。
抽象类只能被继承,不能被实例化。
python自己没有接口,必须使用第三方插件,抽象类abc
抽象类里定义了一个属性,这个抽象类其实跟类是一样的。对象属性的查找方法跟类一样。先从对象本身开始找,没找到找类,类没有再找父类,父类没有再找抽象类。
import abc
class Animal(metaclass=abc.ABCMeta): #只能被继承,不能被实例化
all_type='animal'
@abc.abstractmethod
def run(self):
pass
@abc.abstractmethod
def eat(self):
pass
# animal=Animal()
class People(Animal):
def run(self):
print('people is running')
def eat(self):
print('people is eating')
class Pig(Animal):
def run(self):
print('people is walking')
def eat(self):
print('people is eating')
class Dog(Animal):
def run(self):
print('people is walking')
def eat(self):
print('people is eating')
# peo1=People()
# pig1=Pig()
# dog1=Dog()
# #
# #
# peo1.eat()
# pig1.eat()
# dog1.eat()
#
print(peo1.all_type)
输出:animal
浙公网安备 33010602011771号