where are operators mapped to magic methods in python?

后端 未结 5 1106
無奈伤痛
無奈伤痛 2021-01-02 03:13

I\'ve been reading about magic methods in python, and I\'ve found a lot of info about overriding them and what purpose they serve, but I haven\'t been able to find where i

5条回答
  •  旧时难觅i
    2021-01-02 03:44

    It's non-trivial to pinpoint the single place in CPython sources mapping operator + to special method __add__ because of the levels of abstraction involved.

    As other responded, + is implemented with the BINARY_ADD opcode, which calls PyNumber_Add (except in some specially optimized cases). PyNumber_Add, on the other hand, looks at the tp_as_number member of the type object to get to the PyNumberMethods struct whose nb_add member points to the C function that implements addition.

    This is straightforward for built-in types which define their own nb_add directly, but a bit more convoluted for __add__ defined in Python, which needs to be translated to an appropriate nb_add. This part is handled by typeobject.c: when you define a class that implements __add__, the machinery in typeobject.c installs into object->type->tp_as_number->nb_add a generic function that looks up __add__ on the object and calls it to implement the addition. For the case of __add__, this generic function is called slot_nb_add and is defined using the SLOT1BIN macro.

    As for __new__ and __init__, they are invoked from the __call__ operator of the type object itself (tp_call in CPython-implementation lingo). This is only logical, since in Python you are calling the type to construct an object.

提交回复
热议问题