Chaning instance methods

Tim Peters tim_one at email.msn.com
Thu Apr 8 02:26:17 EDT 1999


[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






More information about the Python-list mailing list