On 6/28/2011 9:20 AM, Steven D'Aprano wrote:
>>> class C:
... def method(self, x):
... return x+1
...
>>> c = C()
>>> c.method = types.MethodType(lambda self, x: x+101, c)
types.MethodType creates a bound method, not a method. A bound method is
a partial or curried function, which is to say, a function.
Herw and below, I am ignoring the fact that the example ignores self. My
comments would be the same for "lambda self,x: return self.value+x"
>>> c.method(1)
The fact that you make the bound function an attribute of the same
object to which it is bound is irrelevant to how it *acts* when called.
It only affect how you *access* it. You could bind it to anything else,
including another instance or a plain name:
d = C()
d.method = types.MethodType(lambda self, x: x+101, c)
d.method(1)
m = types.MethodType(lambda self, x: x+101, c)
m(1)
102
I don't know how rare it is, but it's a useful trick for customising the
behaviour of instances.
As I see it, there are three dichotomies we sometimes need to make:
(1) Instance attributes vs class (shared) attributes.
(2) Computed vs non-computed attributes.
(3) Method attributes (methods) vs non-method/data attributes.
Nicely put so far...
> The three are orthogonal:
Non-class instance function attributes are not methods in any useful sense.
> a staticmethod is a method by virtue of being callable
A 'staticmethod' is a non-method class function attribute. The name is
unfortunate. 'Static' mean 'does not get the dynamic method treatment'.
Strictly speaking, (3) is not truly a dichotomy,
I disagree here. A method is usefully defined as a class function
attribute that gets an automagic first arg when accessed and called
'normally'. In other words, the dichotomy is needed because being a
method affects the meaning of syntax.
since functions and
methods are first class-objects in Python. E.g. one may store a function
as an attribute with the intention of using it as data rather than as a
method.
The fact that one can *also* access a method as a function does not
negate the effect on syntax.
"methods are things you call"
Way too broad, even for attributes. Callable things are methods when
'a.b(c)' causes a to be the first arg of b.
--
Terry Jan Reedy
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com