This question already has an answer here:
- Overriding special methods on an instance 4 answers
- Override a method at instance level 8 answers
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