python @abstractmethod装饰器 [英] python @abstractmethod decorator
问题描述
我已阅读有关抽象基类的python文档:
I have read python docs about abstract base classes:
来自此处:
abc.abstractmethod(function)
指示抽象方法的装饰器。
abc.abstractmethod(function)
A decorator indicating abstract methods.
使用该装饰器要求该类的元类为 ABCMeta
或
从中得出。除非实例化了其所有抽象方法和
属性,否则无法实例化具有源自 ABCMeta
的元类的类。
Using this decorator requires that the class’s metaclass is ABCMeta
or
is derived from it. A class that has a metaclass derived from ABCMeta
cannot be instantiated unless all of its abstract methods and
properties are overridden.
和此处
您可以应用
@abstractmethod
装饰器,必须执行诸如draw()
之类的方法;然后,Python将为未定义方法的
类引发异常。请注意,只有当您实际尝试创建缺少该方法的子类
的实例时,才会引发
。
You can apply the
@abstractmethod
decorator to methods such as draw() that must be implemented; Python will then raise an exception for classes that don’t define the method. Note that the exception is only raised when you actually try to create an instance of a subclass lacking the method.
我已使用此代码对其进行了测试:
I've used this code to test that out:
import abc
class AbstractClass(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def abstractMethod(self):
return
class ConcreteClass(AbstractClass):
def __init__(self):
self.me = "me"
c = ConcreteClass()
c.abstractMethod()
代码运行良好,所以我不明白。如果键入 c.abstractMethod
,我得到:
The code goes fine, so I don't get it. If I type c.abstractMethod
I get:
<bound method ConcreteClass.abstractMethod of <__main__.ConcreteClass object at 0x7f694da1c3d0>>
我在这里缺少什么? ConcreteClass
必须实现抽象方法,但我没有例外。
What I'm missing here? ConcreteClass
must implement the abstract methods, but I get no exception.
推荐答案
您是否使用python3运行该代码?如果是,您应该知道在python 3中声明元类已更改,您应该这样做而是这样:
Are you using python3 to run that code ? if yes you should know that declaring metaclass in python 3 have changes you should do it like this instead:
import abc
class AbstractClass(metaclass=abc.ABCMeta):
@abc.abstractmethod
def abstractMethod(self):
return
这篇关于python @abstractmethod装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!