本文介绍了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").

如果你真的想用抽象方法定义抽象基类,可以使用 abc 模块:

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中的抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 20:17