lundi 14 août 2017

Python `setattr` for functions? [duplicate]

This question already has an answer here:

Let's say I have a class A like so:

class A:
    def __init__(self):
        self.a = a
    def __add__(self, other):
        return other + 1

Then, I run the following code in the console:

>>> a = A()
>>> a.a
<<< 1
>>> setattr(a, 'a', 2)
>>> a.a
<<< 2
>>> a + 2
<<< 3
>>> setattr(a, '__add__', lambda s, o: o - 1)
>>> a + 2
<<< 3

Is there a way to change class functions like this?

Note that it works for non-__ functions, though interestingly enough, if I set it to a function f, the function shouldn't take self as a parameter.





Aucun commentaire:

Enregistrer un commentaire