Chaning instance methods

Tim Peters tim_one at email.msn.com
Fri Apr 9 02:43:31 EDT 1999


[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






More information about the Python-list mailing list