python抽象方法
1.抽象方法的概念
之前我们定义一个基类的时候,如果要求子类必须重写父类中的某一个方法,可以这样做:
定义一个名为Pizza的基类,让其get_radius方法必须被子类继承
class Pizza(object): @staticmethod def get_radius(): raise NotImplementedError
如果子类没有重写该方法就会触发错误
class Sub_Pizza(Pizza): pass Sub_Pizza().get_radius() 错误信息如下: raise NotImplementedError NotImplementedError
但是上述方法的缺点是:如果只实例化了子类,而没有调用方法,NotImplementedError就不会被触发;
抽象方法允许我们在类实例化的同时,通过触发异常来告诉我们那些父类中的方法是必须在子类中重写的,而不需要调用方法才可以知道哪些方法是必须要被重写的;
2.抽象方法的实现
抽象方法的实现使用abc模块实现
定义基类,并指定其中的抽象方法(必须在子类中被重写)
import abc class BasePizza(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def get_radius(self): """Return the ingredient list"""
定义子类继承上述类:
class DietPizza(BasePizza): pass DietPizza() 执行结果: TypeError: Can't instantiate abstract class DietPizza with abstract methods get_radius
由于在子类中没有重写方法get_radius,在实例化子类的时候,报TypeError;
正确代码如下:
class DietPizza(BasePizza): @staticmethod def get_radius(self): return None DietPizza()