3

The python docs on collections.abc has a nice summary table (picture below) with a column named "Mixin Methods." I'm confused by the difference between this column and the previous one.

Is it that "abstract methods" can be custom-made but "mixin methods" have a specific implementation that is fixed in all classes of a given type? If so, where can I find what's in these mixin methods?

enter image description here

Thanks a lot!

Jeffery
  • 629
  • 1
  • 7
  • 17
  • 1
    Read here about mixins in python: https://www.residentmar.io/2019/07/07/python-mixins.html#:~:text=Mixins%20are%20an%20alternative%20class,this%20feature%E2%80%94and%20nothing%20else. – STerliakov May 03 '21 at 13:35

1 Answers1

2

An abstract method is one that you're supposed to implement yourself, if you inherit from any of these classes. For example:

class MyIter(collections.abc.Iterator):

    # We must override __next__ because it's abstract in `Iterator`.
    def __next__(self):
        ...

A mixin is a method whose implementation is already provided in the superclass. So you don't need to override __iter__, because Iterator already implements it.

To continue with the Iterator example: the Iterator class itself is implemented like this (slightly simplified):

class Iterator(Iterable):

    @abc.abstractmethod
    def __next__(self):
        pass

    def __iter__(self):
        return self

We're using abc.abstractmethod to indicate that __next__ is abstract; if you forget to override it in your concrete implementation class, the decorator will cause an exception to be raised.

The __iter__ method, on the other hand, has an implementation that simply returns self, as expected from iterator objects.

Thomas
  • 174,939
  • 50
  • 355
  • 478