我无法运行此代码,因为我得到了异常:
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/