抽象方法未定义
我无法运行这段代码,因为出现了一个异常:
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__'
这个不行呢?我在调试时没有看到输入/输出。
3 个回答
-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)
6
你需要从 abc
这个模块里导入 abstractmethod
。abc
是 Python 自带的一个包,用来处理 抽象基类。
下面是一个例子:
from abc import abstractmethod
class Foo:
def __init():
pass
@abstractmethod
def bar():
pass
55
你只导入了 ABCMeta
from abc import ABCMeta
还需要导入 abstractmethod
from abc import ABCMeta, abstractmethod
这样就没问题了。