abstractmethod is not defined

Question:

I cannot run this code, because I get the exception:

NameError: name 'abstractmethod' is not defined
File "C:TeststrunkPythonTestsAbstractClasses.py", line 12, in <module>
  class MyIterable:
File "C:TeststrunkPythonTestsAbstractClasses.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

Asked By: user278618

||

Answers:

You only imported ABCMeta

from abc import ABCMeta

Also import abstractmethod

from abc import ABCMeta, abstractmethod

and everything should be fine.

Answered By: Sven Marnach

You need to import abstractmethod from abc. abc is the inbuilt Python package for Abstract Base Classes.

An example:

from abc import abstractmethod

class Foo:
    def __init():
        pass
    
    @abstractmethod
    def bar():
        pass
Answered By: gruszczy

You need to change import ABC to 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)
Answered By: yogesh kumar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.