python - 抽象方法未定义

标签 python abstract-class

我无法运行此代码,因为我得到了异常:

NameError: name 'abstractmethod' is not defined
File "C:\Tests\trunk\PythonTests\AbstractClasses.py", line 12, in <module>
  class MyIterable:
File "C:\Tests\trunk\PythonTests\AbstractClasses.py", line 15, in MyIterable
  @abstractmethod

from abc import ABCMeta

class Foo(object):
    def __getitem__(self, index):
        print '__get_item__ Foo'
    def __len__(self):
        print '__len__ Foo'
    def get_iterator(self):
        print 'get_iterator Foo'
        return iter(self)

class MyIterable:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __iter__(self):
        while False:
            yield None

    def get_iterator(self):
        return self.__iter__()

    @classmethod
    def __subclasshook__(cls, C):
        if cls is MyIterable:
            if any("__iter__" in B.__dict__ for B in C.__mro__):
                print "I'm in __subclasshook__"
                return True
        return NotImplemented

MyIterable.register(Foo)

x=Foo()
x.__subclasshook__()

我确定代码没问题,因为我是从 http://docs.python.org/library/abc.html 获得的

编辑

感谢回答,现在可以了,但是为什么

print '__subclasshook__'

这行不通?我没有进入 Debug I/0

最佳答案

你只导入了ABCMeta

from abc import ABCMeta

同时导入abstractmethod

from abc import ABCMeta, abstractmethod

一切都会好起来的。

关于python - 抽象方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4814523/

相关文章:

Python peewee 连接多个表

python - 使用 Pipeline 和 GridSearchCV 完成的训练数量

python - PyCairo Pip 在 Windows 10 上的 python 3.8 中安装失败

c# 派生类型到组合框

python - 类工厂和抽象基类

c++ - 抽象类和纯方法 C++

python 安装工具 : ImportError: cannot import name Library

python - 检查 Python DNS 解析器查询的特定输出

Java 运行前未知的子类型

c# - 抽象类的继承使用不同于为属性定义的类型