Dynamic subclassing ?

Alex Martelli aleax at mac.com
Sun May 13 14:56:34 EDT 2007


manatlan <manatlan at gmail.com> wrote:
   ...
> > def addaclass(aninst, onemoreclass):
> >     aninst.__class__ = type(aninst.__aclass__.__name__,
> >             (aninst.__aclass__, onemoreclass), {})
   ...
> b=gtk.Button("the_label")
> addaclass(b,MoreMethods)
   ...
> "TypeError: __class__ assignment: only for heap types"
> on the last line ...

Ah, yes, a type can be coded in such a way that you simply can't
reassign the __class__ of its instances, and apparently gtk.Button is
coded that way.

If you're keen on __class__ reassigning, you'll have to wrap such
classes before instance creation time, e.g.:

class weirdGtkButton(gtk.Button): pass

and use

b = weirdGtkButton("the label")

to generate the instances.  That, of course, assumes that gtk.Button
isn't ALSO coded in ways that impede subclassing (as for all I know it
might be -- I don't have GTK around to check), in which case instead of
subclassing it you need a trickier wrap-and-hold approach (and you can
never pass isinstance checks, which subclassing would let you pass).


Alex



More information about the Python-list mailing list