Changing the class of an instance

david_ullrich at my-deja.com david_ullrich at my-deja.com
Sun Jul 16 14:40:44 EDT 2000


In article <etdbszzw6wv.fsf at w20-575-115.mit.edu>,
  Alex <cut_me_out at hotmail.com> wrote:
>
> >    Well it's exactly what I was doing once because I was a lot more
> > clever than the guys who said I shouldn't. And then I decided quite
> > suddenly that they were right. (At the end of a _long_ stretch
trying
> > to figure out why the heck something wasn't working - of course the
> > answer is the object in question was very different from the object
it
> > appeared it should be...)
>
> It can have really confusing consequences,

    I don't think "confusing" is the right word. Although I'm
fairly certain I won't get the words right: It destroys the...
maybe the word is "encapsulation" or "modularity" or something -
it means that you cannot verify things are correct by just
looking at things locally. When you write

def AClass:
  def AMethod(self):
    <some code>

you can't know that AMethod is correct just by inspecting
<some code>, because you have no idea whether <some code>
is what's executed when AMethod is called.

> but it's still too useful
for
> me to abandon.  If you have a class which takes a long time to
> instantiate (e.g., you have to load a lot of statistical data into
> memory,) then having a script like
>
> class C:
>     pass
>
> if 't' not in dir():
>     t = C()
>
> t.__class__ = C
> t.experiment_with_instance()
>
> can really decrease your turn-around time when you're debugging -- you
> can change t's methods around behind its back without changing its
data.

     Not sure what sort of debugging we're referring to. If you're
trying to figure out how to do something, as opposed to writing
code meant to be used later, that's different. I'm not sure whether
you're talking about temporary experimental code or "real" code;
the post that started this was evidently talking about real code.
In temporary code I suppose changing __class__ could be more
convenient simply because it possibly takes a few fewer lines
to write - in real code I don't see why changing the value
of aninstance.__class__ is better than creating a second instance
of the new class. Possibly I missed it, but I haven't seen any
reason given why changing __class__ is better than creating
a new instance (I don't think that the time it takes to load
data counts, there's no reason you have to reload the data
instead of referring to the data already loaded.)

> Alex.
>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list