未定义abstractmethod [英] abstractmethod is not defined

查看:134
本文介绍了未定义abstractmethod的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I cannot run this code, because I get the exception:

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

I'm sure that code is ok, because I got it from http://docs.python.org/library/abc.html

编辑

感谢您的回答,现在可以使用了,但是为什么

Thanks for answer, it works now, but why

print '__subclasshook__'

这不起作用吗?我没有进入调试I / 0

this doesn't work ? I don't get in Debug I/0

推荐答案

您仅导入了 ABCMeta

from abc import ABCMeta

还导入抽象方法

from abc import ABCMeta, abstractmethod

一切都应该没问题。

这篇关于未定义abstractmethod的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆