我已阅读有关抽象基类的 python 文档:
来自 here :
abc.abstractmethod(function)
A decorator indicating abstract methods.Using this decorator requires that the class’s metaclass is
ABCMeta
or is derived from it. A class that has a metaclass derived fromABCMeta
cannot be instantiated unless all of its abstract methods and properties are overridden.
还有 here
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.
我已经使用此代码进行了测试:
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
我得到:
<bound method ConcreteClass.abstractMethod of <__main__.ConcreteClass object at 0x7f694da1c3d0>>
我在这里缺少什么? ConcreteClass
必须实现抽象方法,我也不异常(exception)。
最佳答案
您是否使用 python3 来运行该代码?如果是,你应该知道在 python3 中声明元类 have changes你应该这样做:
import abc
class AbstractClass(metaclass=abc.ABCMeta):
@abc.abstractmethod
def abstractMethod(self):
return
完整的代码和答案背后的解释是:
import abc
class AbstractClass(metaclass=abc.ABCMeta):
@abc.abstractmethod
def abstractMethod(self):
return
class ConcreteClass(AbstractClass):
def __init__(self):
self.me = "me"
# Will get a TypeError without the following two lines:
# def abstractMethod(self):
# return 0
c = ConcreteClass()
c.abstractMethod()
如果没有为ConcreteClass
定义abstractMethod
,运行上述代码时会引发如下异常:TypeError: Can't instantiate abstract class ConcreteClass with抽象方法 abstractMethod
关于python @abstractmethod 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7196376/