我无法运行此代码,因为我得到了异常:
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
答案 0 :(得分:32)
您只导入了ABCMeta
from abc import ABCMeta
还导入abstractmethod
from abc import ABCMeta, abstractmethod
一切都应该没问题。
答案 1 :(得分:3)
您需要从abstractmethod
导入abc
。
答案 2 :(得分:-1)
您需要将导入ABC更改为ABCMeta
from abc import ABCMeta, abstractmethod
class AbstractClassExample(ABCMeta):
def __init__(self, value):
self.value = value
super().__init__()
@abstractmethod
def do_something(self):
print("do_something")
class DoAdd42(AbstractClassExample):
print("DoAdd42")
x = DoAdd42(4)