Monkey patching a @property

后端 未结 7 1895
慢半拍i
慢半拍i 2021-02-03 18:33

Is it at all possible to monkey patch the value of a @property of an instance of a class that I do not control?

class Foo:
    @property
    def bar         


        
7条回答
  •  悲&欢浪女
    2021-02-03 18:53

    Subclass the base class (Foo) and change single instance's class to match the 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
    

提交回复
热议问题