From: tim_one at email.msn.com (Tim Peters)
Date: Fri, 9 Apr 1999 06:43:31 GMT
Subject: Chaning instance methods
In-Reply-To: <370CC27E.ED2D0D59@inrialpes.fr>
References: <370CC27E.ED2D0D59@inrialpes.fr>
Message-ID: <000f01be8254$489a7b60$14a02299@tim>
Content-Length: 1585
X-UID: 508                                                  

[Tim]
> When I signed my exposition of instance-method trickery "subclassing-is-
> a-lot-easier-ly y'rs", I had exactly this in mind:
>
> class Bar(Foo):
>     def m(self):
>         print "m2"
>
> f = Bar()

[Vladimir Marangozov]
> Careful!

I usually am <wink>.

> We'll eventually see what you had exactly in mind if you change the
> last line from
>
> (1) f = Bar()
>
> to
>
> (2) f.__class__ = Bar

Nope, I didn't have that in mind at all.  Turns out (to judge from his
followup) that this is what *Jody* had in mind, but not me.  Most people who
have asked this question over the years really could have done just fine
using vanilla inheritance from the start, perhaps augmented by a factory
function to choose the object's class with more care.

> While (1) resets f's internal state and makes a brand new instance,
> (2) preserves that state (which reflects f's past existence as an
> instance of Foo) by changing only its interface to that of Bar
> "on the fly". The difference is quite fundamental.

Fundamental is too weak a word, but I know what you mean <wink>.  Changing
an object's class after-the-fact is not an approach I'd recommend to anyone.
That doesn't mean I don't approve of it <wink>, it's just that people far
too often start playing absurd tricks with Python's highly dynamic features
when straightforward methods work fine.

> We all knew that you meant (2) in your sig, but making it slightly
> more explicit does not hurt :-)

the-things-we-know-that-aren't-true-could-fill-a-bottomless-
    ocean-to-a-depth-of-half-an-invisible-inch-ly y'rs  - tim






