Python 这个抽象方法修饰符

我读过关于抽象基类的 python 文档:

来自 给你:

abc.abstractmethod(function) 表示抽象方法的修饰符。

使用此修饰符需要类的元类为 ABCMeta或 一个类,它有一个从 ABCMeta派生的元类 不能实例化,除非它的所有抽象方法和 属性被重写。

还有 给你

您可以将 @abstractmethod修饰符应用于诸如 draw ()之类的方法 必须实现的; 然后 Python 将为 没有定义方法的类。请注意,异常只是 实际尝试创建子类的实例时引发 缺乏方法。

我用这段代码测试了一下:

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 必须的实现抽象方法,但我没有得到例外。

120110 次浏览

Are you using python3 to run that code? If yes, you should know that declaring metaclass in python3 have changes you should do it like this instead:

import abc


class AbstractClass(metaclass=abc.ABCMeta):


@abc.abstractmethod
def abstractMethod(self):
return

The full code and the explanation behind the answer is:

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()

If abstractMethod is not defined for ConcreteClass, the following exception will be raised when running the above code: TypeError: Can't instantiate abstract class ConcreteClass with abstract methods abstractMethod

Import ABC from abc and make your own abstract class a child of ABC can help make the code look cleaner.

from abc import ABC, abstractmethod


class AbstractClass(ABC):


@abstractmethod
def abstractMethod(self):
return


class ConcreteClass(AbstractClass):
def __init__(self):
self.me = "me"


# The following would raise a TypeError complaining
# abstractMethod is not implemented
c = ConcreteClass()

Tested with Python 3.6