Python中的抽象方法 [英] Abstract methods in Python

查看:106
本文介绍了Python中的抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要类似Python(3.2)中的abstract protected方法的东西:

I need something like an abstract protected method in Python (3.2):

class Abstract:
    def use_concrete_implementation(self):
        print(self._concrete_method())

    def _concrete_method(self):
        raise NotImplementedError()


class Concrete(Abstract):
    def _concrete_method(self):
        return 2 * 3

定义抽象"方法仅引发NotImplementedError真的有用吗?

Is it actually useful to define an "abstract" method only to raise a NotImplementedError?

使用下划线表示抽象方法(在其他语言中为protected)是否是一种好的样式?

Is it good style to use an underscore for abstract methods, that would be protected in other languages?

抽象基类(abc)会改善什么吗?

Would an abstract base class (abc) improve anything?

推荐答案

在Python中,通常避免一起使用此类抽象方法.您可以通过文档定义接口,然后简单地假设传入的对象满足该接口(鸭式打字").

In Python, you usually avoid having such abstract methods alltogether. You define an interface by the documentation, and simply assume the objects that are passed in fulfil that interface ("duck typing").

如果您确实想使用抽象方法定义抽象基类,则可以使用

If you really want to define an abstract base class with abstract methods, this can be done using the abc module:

from abc import ABCMeta, abstractmethod

class Abstract(metaclass=ABCMeta):
    def use_concrete_implementation(self):
        print(self._concrete_method())

    @abstractmethod
    def _concrete_method(self):
        pass

class Concrete(Abstract):
    def _concrete_method(self):
        return 2 * 3

同样,这不是Python常用的处理方式. abc模块的主要目标之一是引入一种重载isinstance()的机制,但是通常避免使用isinstance()检查,而采用鸭子类型.如果需要,请使用它,但不要将其用作定义接口的通用模式.

Again, that is not the usual Python way to do things. One of the main objectives of the abc module was to introduce a mechanism to overload isinstance(), but isinstance() checks are normally avoided in favour of duck typing. Use it if you need it, but not as a general pattern for defining interfaces.

这篇关于Python中的抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆