subclassing extension type and assignment to __class__
Lenard Lindstrom
len-1 at telus.net
Sun Nov 28 14:02:16 EST 2004
gregory lielens <gregory.lielens at fft.be> writes:
> Thanks for your answer, it means I am not the only one having this
> kind of problem...
> > I have just run into the same thing with the builtin list type. The trick
> > was not to declare my subclass directly from list, but rather a subclass
> > of list. So try this:
> > class PClassBase(_PClass):
> > pass
> > class PClass(PClassBase):
> > ...
> > class PClass2(PClassBase):
> > ...
> >
> I think here you mean PClass2(PClassBase2), with a
> PClassBase2(_PClass2): In my example the 2 class do not inherit fro
> the same base class...
> > Why? I cannot say other than I have noted that Python new-style classes
> > and extension types are not quite the same thing. That is, a new-style
> > class is a particular kind of extension type.
>
> I see how it can help me making PClassBase a PClass (or any type
> derived from PClassBase), but what I fail to see is how this will
> allow me to change a _PClass into one of it's derived types: this is
> necessary for updating methods of _PClass2 that return object of type
> _PClass (and on this I do not have much control, both _PClass and
> _PClass2 and all of their methods are implemented in C++). To updates
> theses methods for the pure python derived class PClass2, I have to
> make them return the python class PClass instead of the original
> _PClass, which means I still have to transform a _PClass object into
> its derived type PClassBase or PClass, and at this time things go
> pear-shaped :-(....or is there something I miss?
>
Sorry for the confusion. This looks like a situation best handled with
embedding rather than inheritance. The PClass and PClass2 wrapper classes
can share whatever relationship _PClass and _PClass2 share.
class PClass:
def __init__(inst=None):
if inst is None:
inst = _PClass()
self._inst = inst
def override_method(self, ...):
self._inst.override_method(...)
def new_method(self, ...):
...
class PClass2:
self._inst = _PClass2()
def troublesome_method(self):
base = PClass(self._inst.troublesome_method())
...
return base
Alternatively you could provide a way to pass PClass back to the extension module
for _PClass2.troublesome_method to use instead of _PClass when creating a return
object. But the embedding approach seems more appropriate when _PClass is not to
be used directly.
Lenard Lindstrom
<len-l at telus.net>
More information about the Python-list
mailing list