2011-01-27 34 views
12

tôi không thể chạy mã này, bởi vì tôi có được ngoại lệ:abstractmethod không được định nghĩa

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__() 

tôi chắc chắn rằng mã đó là ok, vì tôi đã nhận nó từ http://docs.python.org/library/abc.html

EDIT

Cảm ơn bạn đã trả lời, nó hoạt động ngay bây giờ, nhưng tại sao

print '__subclasshook__' 

tính năng này không hoạt động? Tôi không nhận được trong Debug I/0

+0

Tại sao 'in' tôi ở dạng __subclasshook __ ''không hoạt động? Bạn đã thực sự dành thời gian để đếm các ký tự trích dẫn '''? –

+0

xin lỗi, thực tế có '__subclasshook__'. Tôi đã viết ở đây một văn bản khác để làm rõ: / – user278618

Trả lời

23

Bạn chỉ nhập khẩu ABCMeta

from abc import ABCMeta 

Cũng nhập abstractmethod

from abc import ABCMeta, abstractmethod 

và tất cả mọi thứ nên được tốt.

2

Bạn cần nhập abstractmethod từ abc.

Các vấn đề liên quan