Calling dunder methods manually

eryk sun eryksun at gmail.com
Thu Apr 13 03:43:08 EDT 2017


On Thu, Apr 13, 2017 at 5:29 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> my_number.__add__(another_number)
>
> The short answer is:
>
> NO! In general, you shouldn't do it.

For example:

    class C:
        def __add__(self, other):
            return NotImplemented

    class D:
        def __radd__(self, other):
            return 42

    >>> C().__add__(D())
    NotImplemented

    >>> C() + D()
    42

The functions in the operator module implement abstract behavior (e.g.
PyNumber_Add in CPython):

    >>> operator.__add__(C(), D())
    42


More information about the Python-list mailing list