Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的抽象方法_Python_Oop_Python 3.x_Abstract Class - Fatal编程技术网

Python中的抽象方法

Python中的抽象方法,python,oop,python-3.x,abstract-class,Python,Oop,Python 3.x,Abstract Class,我需要Python(3.2)中类似于抽象保护的方法的东西: 定义一个“抽象”方法只是为了引发一个NotImplementedError,实际上有用吗 在抽象方法中使用下划线是一种好的风格吗?这种方法在其他语言中是受保护的 抽象基类(abc)会改进什么吗?基本上,基类中不需要空方法。就这样做吧: class Abstract: def use_concrete_implementation(self): print(self._concrete_method()) cla

我需要Python(3.2)中类似于
抽象保护的
方法的东西:

定义一个“抽象”方法只是为了引发一个NotImplementedError,实际上有用吗

在抽象方法中使用下划线是一种好的风格吗?这种方法在其他语言中是受保护的


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

基本上,基类中不需要空方法。就这样做吧:

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

class Concrete(Abstract):
    def _concrete_method(self):
        return 2 * 3
事实上,在Python中,您通常甚至不需要基类。由于所有调用都是动态解析的,因此如果该方法存在,将调用它,如果不存在,将引发
AttributeError


注意:在文档中提到
\u concrete\u method
需要在子类中实现是很重要的。

在Python中,通常避免将这些抽象方法放在一起。您可以通过文档定义一个接口,并简单地假设传入该接口的对象(“duck typing”)

如果您确实想用抽象方法定义抽象基类,可以使用以下模块:

同样,这不是Python通常的做事方式。
abc
模块的主要目标之一是引入一种机制来重载
isinstance()
,但是通常避免进行
isinstance()
检查,而采用duck类型。如果需要,可以使用它,但不能作为定义接口的通用模式。

如果有疑问

没有下划线。只需将“抽象方法”定义为引发NotImplementedError的一行代码:

class Abstract():
    def ConcreteMethod(self):
        raise NotImplementedError("error message")

一开始这不是一个“python问题”,这一点很重要。但是为什么不用代码本身“记录”并在“抽象”方法的主体中提出一个
NotImplementedError
。如果将其实现为
NotImplementedError
,则会得到后一个异常。如果您觉得不同的错误消息值得附加代码,那么请继续:“我经常认为<代码>属性错误< /代码>已经足够清楚,但是可能有一些情况您希望事情更加明确。<代码>类抽象(Meta Case= ABCMETA)< /C> >仅在Python 3中工作,对吗?但Guido对抽象的“受保护”方法使用下划线;-)还有Guido:)你为什么要命名一个抽象方法
Conrete
?@Ethan Furman:因为程序员应该实现这个名称的方法。抽象类必须始终使用“待以后使用”的名称来命名抽象方法。@pepr:哦,对了,当我问这个问题时,我能说我真的很累吗?花园疲劳,也许吧?;)
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
class Abstract():
    def ConcreteMethod(self):
        raise NotImplementedError("error message")