Subclassing by monkey-patching
Peter Otten
__peter__ at web.de
Sun Sep 5 03:53:39 EDT 2010
Arnaud Delobelle wrote:
> Jason <jason.heeris at gmail.com> writes:
> [...]
>> Is there a way I can write the subclass but then somehow... extend an
>> existing instance all at once rather than monkeypatch methods on one
>> by one? So I could take an existing instance of a FileMonitor and make
>> it an instance of my subclass? This would even allow me to override
>> the gio.File.monitor_directory() method to take the monitor returned
>> by the original method and decide whether to make it recursive based
>> on a parameter passed to monitor_directory().
>
> There is a straightforward way:
>
>>>> class A(object):
> ... def __init__(self, x):
> ... self.x = x
> ...
>>>> class B(A):
> ... def x2(self):
> ... return self.x**2
> ...
>>>> a = A(42) # Create an instance of A
>>>> a.__class__ = B # Change its class to B
>>>> a.x2()
> 1764
>
> However, I've never really tried it so I don't know what ways it could
> break.
I think this is fine for classes written Python but won't work here:
>>> m = gio.File(".").monitor_directory()
>>> C = type(m)
>>> class CC(C):
... def whatever(self):
... print 42
...
>>> m.__class__ = CC
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __class__ assignment: '__main__.GInotifyDirectoryMonitor'
deallocator differs from 'CC'
A possible alternative may be a class that wraps a FileMonitor instead of
subclassing it.
Peter
More information about the Python-list
mailing list