Method / Functions - What are the differences?
Alf P. Steinbach
alfps at start.no
Sun Feb 28 09:08:49 EST 2010
* Michael Rudolf:
> Out of curiosity I tried this and it actually worked as expected:
>
> >>> class T(object):
> x=[]
> foo=x.append
> def f(self):
> return self.x
>
>
> >>> t=T()
> >>> t.f()
> []
> >>> T.foo(1)
> >>> t.f()
> [1]
> >>>
>
> At first I thought "hehe, always fun to play around with python. Might
> be useful sometimes" - but then It really confused me what I did. I
> mean: f is what we call a method, right? But was is foo?
foo is (refers to) an object that supports call notation and that forwards calls
somewhere else, in this case to append on a list.
You might call it (descriptive) a call forwarder, or (C# or general terminology)
a delegate, or (Python 2.x) a bound method.
<example>
>>> "Hello".upper
<built-in method upper of str object at 0x00BA16E0>
>>> f = "Hello".upper
>>> f
<built-in method upper of str object at 0x00BA16E0>
>>> f()
'HELLO'
>>>
>>>
>>>
>>> f.__self__
'Hello'
>>> f.__call__
<method-wrapper '__call__' of builtin_function_or_method object at 0x00BDD170>
>>> print( f.__doc__ )
S.upper() -> str
Return a copy of S converted to uppercase.
>>> _
</example>
A common use for delegates is as command handlers in a GUI application, and in
general for event notifications.
Cheers & hth.,
- Alf
More information about the Python-list
mailing list