new.instancemethod

Alex Martelli aleaxit at yahoo.com
Wed May 16 17:22:54 EDT 2001


<James_Althoff at i2.com> wrote in message
news:mailman.990039435.21839.python-list at python.org...
    ...
> True.  On the other hand, Python does support instance-specific methods.

You mean bound-methods, right?

> So what is a nice example usage of this capability and what is a good
> practice for its implementation?

What capability, exactly?  Bound methods, unbound ones, the new
module...?

> In GUI code I often want to do something
> like giving "instance-specific behavior" to each button on a panel.  But
in
> practice, if I have two buttons, button1 and button2, lets say, I usually
> assign two different handler methods, "handleButton1" and "handleButton2"
> -- one to each button -- that are defined as part of some controller
class.

Why that, rather than bound methods directly?

> So I'm using an instance-specific attribute (that references a bound
method
> -- which is extremely useful) but it's not an "instance-specific method"
in
> the sense that the "im_self" part of the bound method refers to the
> controller object and not to the button object itself.  So, what would be
a
> good example of an instance-specific method where the "im_self" of the
> bound method object actually points back to the object of which it is an
> instance-specific method (to describe the concept as poorly as possible
;-)
> ).  And then, how does one build such a method without using module "new"?

I'm having something of a hard time understanding exactly what you
are asking, but I'll give it a try.  I guess you mean something like
(it can be a bit more concise with nested scopes...):

def makeBound(object, message):
    def emit(object, message=message):
        print "Hello and %s from %s"%(
            message, object.name)
    object.__class__._my_temp=emit
    result = object._my_temp
    del object.__class__._my_temp
    return result

then

obj.greet = makeBound(obj, "welcome")

...?

The new module is better (no need to use a temporary _my_temp
attribute of the class object, &c) but this works too.

Now you may call obj.greet() or obj.greet("good luck"), etc.  Maybe
preferable (and maybe not) to:

def makePseudoBound(obj, msg):
    def emit(msg=msg, obj=obj):
        print "Hello and %s from %s"%(
            msg, obj.name)
    return emit
then
obj.greet = makeBound(obj, "welcome")

where the 'binding' is simulated through default arguments, or
nested scopes, etc.


> Any good examples from practice?

Not that comes to mind.  I have never had the need to store a
bound method as an attribute of the object to which it was
bound -- it seems more common, if stored it needs to be, to
store it elsewhere.  Nor have I ever actually needed this
new-eschewing black magic, nor can I think why one would
prefer that to module new.


Alex






More information about the Python-list mailing list