A 'Python like' language

Andrew Bennetts andrew-pythonlist at puzzling.org
Tue Mar 30 04:44:33 EST 2004


On Mon, Mar 29, 2004 at 10:46:42PM -0800, Mark Hahn wrote:
> I need a better understanding of this.  You are suggesting the self stay
> with a function like a closure of sorts?
> 
> In my mind, anytime you say obj.func(), func is called on obj, no ifs ands
> or buts.  How could it be otherwise?  When would you want it otherwise?

How is it possible to store a function from some object in another object
for later use, e.g. as a callback?

i.e. in Python syntax:

    class C:
        def __init__(self, callbackFunc):
            self.callbackFunc = callbackFunc
    
        def fireCallback(self):
            self.callbackFunc()
    
    c = C(someobj.method)
    
    ...
    
    c.fireCallback()

> You say fragile.  What breaks?

The fragility I see is that storing a function in a variable doesn't modify
the function, but storing it as an attribute of an object does, i.e.

    f = someobj.method
    x = f
    x()

behaves differently to:

    otherobj.f = someobj.method
    x = otherobj.f
    x()

Python solves this by wrapping functions found in classes as (un)bound
methods (which keep track of the instance they were accessed from) -- but
functions found on *instances* (i.e. they are in the dict of the instance,
but not the class) are left alone.  It works well :)

-Andrew.





More information about the Python-list mailing list