Stefan Kuzminski wrote:

> ahh, this changes the inheritence for *all* instances of of the class, not
> just this instance!  it seems like the '__class__' attribute is shared
> across all instances of a specific class..
>
> S

Well, sort of...  the __class__ attribute is a reference to the class object
that a given object is an instance of.   (In other words, given  a = A(), then
a.__class__ is A.)  Since each class object is a separate class, then yes, all
instances of A refer to the same class object in their __class__ attribute.
When you modify a.__class__.__bases__, that's equivalent to modifying
A.__bases__ -- in other words, you're changing the class object itself, not the
instance object.

Given a class heirarchy like this:

class A:
    pass
class B:
    pass
class C(A):
    pass

Then C.__bases__ is A; if you change C.__bases__ to B, then all instances of C
will then take on the new base class.  I'm pretty sure that it's not possible
to have some instances of C have a B base and some instances of C have an A
base.  That would (ISTM) violate the whole meaning of class membership and
inheritance.  (Wouldn't you be shocked to find that some dogs are not mammals?)

You *might*, however, be able to do something like

import copy
D = copy.deepcopy(C)
D.__bases__ = B
c.__class__ = D

In other words, create a new class that's a copy of C, change the new class's
base class, and then make your instance into an instance of the new class.  I
don't know if the copy module will actually work for this, though if it doesn't
then you might find something useful in the new module.

Of course, even if it *does* work, there's also the question of whether it's a
good idea.  Mucking around with __class__ and __bases__ can be useful, but it's
definately black magic, and as such, is very liable to backfire on you if
you're not *very* careful.  (And if others later use your code, they're
unlikely to know *how* to be properly careful....)

Jeff Shannon
Technician/Programmer
Credit International


_______________________________________________
ActivePython mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/listinfo/activepython

Reply via email to