python - Monkey patching a @property -
is @ possible monkey patch value of @property
of instance of class not control?
class foo: @property def bar(self): return here().be['dragons'] f = foo() print(f.bar) # baz f.bar = 42 # magic! print(f.bar) # 42
obviously above produce error when trying assign f.bar
. # magic!
possible in way? implementation details of @property
black box , not indirectly monkey-patchable. entire method call needs replaced. needs affect single instance (class-level patching okay if inevitable, changed behaviour must selectively affect given instance, not instances of class).
subclass base class (foo
) , change single instance's class match new subclass using __class__
attribute:
>>> class foo: ... @property ... def bar(self): ... return 'foo.bar' ... >>> f = foo() >>> f.bar 'foo.bar' >>> class _subfoo(foo): ... bar = 0 ... >>> f.__class__ = _subfoo >>> f.bar 0 >>> f.bar = 42 >>> f.bar 42
Comments
Post a Comment