The standard document about abc, and other tutorials I read all use examples that defines a abstract base class without inheriting from object.
class Foo(object):
def __getitem__(self, index):
...
def __len__(self):
...
def get_iterator(self):
return iter(self)
class MyIterable:
__metaclass__ = ABCMeta
@abstractmethod
def __iter__(self):
while False:
yield None
In the past I always let my class inherit object to have new-style class. Should I do the same with ABC?
Declaring the metaclass of MyIterable to be ABCMeta ensures that instances of MyIterable (or more appropriately, subclasses of MyIterable since it is an Abstract Base Class) will be the "new" style. If you were to create an instance of a subclass of MyIterable as seen below, it would behave as a new style class.
class SubIterable(MyIterable):
def __iter__(self):
# your implementation here
...
>>> type(SubIterable())
<type '__main__'.MyIterable>
If MyIterable were indeed an "old" style class, type(SubIterable()) would return <type 'instance'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With