__set_name__ equivalent for instance

Dieter Maurer dieter at handshake.de
Thu Nov 16 14:00:46 EST 2023


Dom Grigonis wrote at 2023-11-16 20:12 +0200:
>What I am interested in is a callback.
>Preferably just after methods get bound. So in `object.__new__`.

>I have done it via metaclass, but it is not ideal as there would be too much overhead.
>
>I think what I am looking for is custom method binding.

Methods are not bound during instance creation, they are bound during
access.

You can use descriptors to implement "custom method binding".

Descriptors are defined on the class (and do not behave as
descriptors when defined on instances).
Thus, you would need a metaclass or `__inist_subclass__` is you
want your "custom method binding" globally.


For many methods (but usually not the `__...__` methods),
you can take over the binding in `__new__` or `__init__`
and populate the instance with prebound methods.


More information about the Python-list mailing list