抽象类
抽象类
抽象类:本质就是把多个类(People,Dog,Pig),抽取他们比较像的部分,最后得到一个父类(Animal),子类继承父类,让子类在继承的时候必须实现父类规定的一些方法(run、eat)。
具体实现需要借助第三方模块abc。
抽象类本质还是类,只能被继承,不能实例化
好处是:做一种归一化,统一标准,降低使用者的使用复杂度。
class Animal:
def run(self):
pass
def eat(self):
pass
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")
people = People()
pig = Pig()
dog = Dog()
people.eat()
pig.eat()
dog.eat()
import abc,@abc.abstractclassmethod后,如果子类不定义@下面的属性,程序就会报错。
import abc
class Animal(metaclass=abc.ABCMeta): # 做成抽象类,只能被继承,不能实例化
@abc.abstractclassmethod # 只定义规范,不实现具体效果
def run(self):
pass
@abc.abstractclassmethod # 只定义规范,不实现具体效果
def eat(self):
pass
class People(Animal):
def run(self):
print("people is walking")
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")
people = People()
# pig = Pig()
# dog = Dog()
# people.eat()
# pig.eat()
# dog.eat()
TypeError: Can't instantiate abstract class People with abstract methods eat

浙公网安备 33010602011771号