new.instancemethod

James_Althoff at i2.com James_Althoff at i2.com
Fri May 18 13:50:31 EDT 2001


Alex Martelli wrote:

<snip>

>In Python it's trivial.  Say the behavior I'm studying is: "for a hand
which
>by basic methods would bid a natural invitational 2NT, bid 3NT instead
>if it has a 6-carder or longer suit header by the A".  The module will
>easily find "all hands with a 6-carder or longer headed by A" and for
>them, and them only, change the .ownbid method:

Well, to be *really* convinced I think I would have to map this example
into something that was more suited (oh shame) to my own card-playing-skill
level.  Let's see now, in "Go Fish" that would be like . . .  :-)

<snip>

>A class-centered person would no doubt prefer a class-focused approach
>here too:

I guess I'm a just an "old school" (well, *old* for sure) class-centered
person.  The thing that I really like about the approach below is that --
assuming that the example is modified slightly so that the class "Tweak" is
pulled out of the function definition and is available in the module -- I
could then define a second "instance-specific subclass" and have that one
use "Tweak" as a base class and reuse (tweak?) the Tweak.ownbid method.
Although you might not always need such reuse, I really like the ability to
extend things in the future by taking advantage of the "framework for
reuse" that a class gives you -- even if a class only has a singleton
instance.  That's one of the big reasons I really like methods in a class
compared to functions outside of a class (because you can override the
method, call the super class method, add some behavior, etc. -- damn the
"fragile base classes", full speed ahead! ;-)).

Anyway, I really like the example below.  Creating a subclass on the fly
and then changing the __class__ of an instance -- if used judiciously --
seems like a really useful approach for instance-specific behavior in
certain cases.  Thanks, Alex.

>
>def tweak_ownbid(obj):
>    Base = obj.__class__
>    class Tweak(Base):
>        Base = Base
>        def ownbid(self, bidding_history):
>            bid = Base.ownbid(self, bidding_history)
>        # &c, snipped
>    obj.__class__ = Tweak
>
>this has its advantages, but keeping these per-method decorators
>as instance-specific/method-specific entries has pluses too, most
>particularly if you also start removing and juggling them around
>more freely.
>
>
>Alex

Jim





More information about the Python-list mailing list