抽象方法未定义
我无法运行此代码,因为我得到了异常:
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
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__()
I'm sure that code is ok, because I got it from http://docs.python.org/library/abc.html
EDIT
Thanks for answer, it works now, but why
print '__subclasshook__'
this doesn't work ? I don't get in Debug I/0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只导入了
ABCMeta
还导入了
abstractmethod
,一切都应该没问题。
You only imported
ABCMeta
Also import
abstractmethod
and everything should be fine.
您需要从
abc
导入abstractmethod
。abc
是抽象基类。一个例子:
You need to import
abstractmethod
fromabc
.abc
is the inbuilt Python package for Abstract Base Classes.An example:
您需要将 import ABC 更改为 ABCMeta
You need to change import ABC to ABCMeta