Injecting methods into instance / class

Morten W. Petersen morphex at gmail.com
Sun Dec 2 13:15:48 EST 2018


Hi Duncan.

On Sun, Dec 2, 2018 at 7:02 PM duncan smith <duncan at invalid.invalid> wrote:

> Hello,
>       I have a lot of functions that take an instance of a particular
> class as the first argument. I want to create corresponding methods in
> the class. I have tried the following, which (when called from __init__)
> creates the relevant methods in an instance (Python 3.6).
>
>
> def init_methods(self):
>     for func_name, method_name in [('add', '__add__'),
>                                    ('subtract', '__sub__')]:
>         setattr(self, method_name,
> types.MethodType(globals()[func_name], self))
>
>
> The problem is that e.g.
>
> x.__sub__(y)
>
> works as expected, but
>
> x - y
>
> does not (because special methods are looked up in the class rather than
> the instance).
>
> I have tried to find examples of injecting methods into classes without
> success. I have tried a few things that intuition suggested might work,
> but didn't - like removing the first line above, dedenting and replacing
> self with the class. This is only to save typing and make the code
> cleaner, but I would like to get it right. Any pointers appreciated. TIA.
>

Doesn't this explain things fairly well?

https://docs.python.org/3/reference/datamodel.html#special-lookup

>From what I gather, some methods are always called from the
class object, rather than (instance created from) class object.

-Morten


-- 
Videos at https://www.youtube.com/user/TheBlogologue
Twittering at http://twitter.com/blogologue
Blogging at http://blogologue.com
Playing music at https://soundcloud.com/morten-w-petersen
Also playing music and podcasting here:
http://www.mixcloud.com/morten-w-petersen/
On Google+ here https://plus.google.com/107781930037068750156
On Instagram at https://instagram.com/morphexx/



More information about the Python-list mailing list