From: tim_one at email.msn.com (Tim Peters)
Date: Thu, 8 Apr 1999 06:26:17 GMT
Subject: Chaning instance methods
In-Reply-To: <370C2904.A6F4BD54@inrialpes.fr>
References: <370C2904.A6F4BD54@inrialpes.fr>
Message-ID: <000801be8188$b59aa9a0$749e2299@tim>
X-UID: 1679                                                  

[Vladimir Marangozov, with much good advice]
> ...
> Thus we arrive at the easy & boring solution, which goes along
> these lines:
> (it's an instance hack too, but a recognized one in metaobject
> communities)
>
> >>> class Foo:
> ...     def m(self):
> ...         print "Foo.m"
> ...
> >>> f = Foo()
> >>> f.m()
> Foo.m
> >>>
> >>> def m2(self):
> ...     print "m2"
> ...
> >>> class Bar(f.__class__): pass
> ...
> >>> Bar.m = m2
> >>>
> >>> f.__class__ = Bar # f changes its camp
> >>> f.m()
> m2

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()

Over the years, *most* people who have asked questions akin to Jody's really
could have done this-- the *wholly* obvious thing! --from the start.  Maybe
it's a  "define a whole new class just to change one method?!" reluctance
left over from C++ <0.9 wink>.

catering-to-laziness-can-be-counterproductive-ly y'rs  - tim






