gpt4 book ai didi

python - 抽象方法未定义

转载 作者:IT老高 更新时间:2023-10-28 20:44:55 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com