reflection - Python `setattr` for functions? -
this question has answer here:
- overriding special methods on instance 4 answers
- override method @ instance level 8 answers
let's have class a
so:
class a: def __init__(self): self.a = def __add__(self, other): return other + 1
then, run following code in console:
>>> = a() >>> a.a <<< 1 >>> setattr(a, 'a', 2) >>> a.a <<< 2 >>> + 2 <<< 3 >>> setattr(a, '__add__', lambda s, o: o - 1) >>> + 2 <<< 3
is there way change class functions this?
note works non-__
functions, though interestingly enough, if set function f
, function shouldn't take self
parameter.
Comments
Post a Comment