Function mistaken for a method
Eric Brunel
eric_brunel at despammed.com
Thu Jun 1 07:12:18 EDT 2006
Hi all,
I just stepped on a thing that I can't explain. Here is some code showing
the problem:
-----------------------------
class C:
f = None
def __init__(self):
if self.f is not None:
self.x = self.f(0)
else:
self.x = 0
class C1(C):
f = int
class C2(C):
f = lambda x: x != 0
o1 = C1()
print o1.x
o2 = C2()
print o2.x
-----------------------------
Basically, I want an optional variant function across sub-classes of the
same class. I did it like in C1 for a start, then I needed something like
C2. The result is... surprising:
0
Traceback (most recent call last):
File "func-vs-meth.py", line 18, in ?
o2 = C2()
File "func-vs-meth.py", line 5, in __init__
self.x = self.f(0)
TypeError: <lambda>() takes exactly 1 argument (2 given)
So the first works and o1.x is actually 0. But the second fails because
self is also being passed as the first argument to the lambda. Defining a
"real" function doesn't help: the error is the same.
My actual question is: why does it work in one case and not in the other?
As I see it, int is just a function with one parameter, and the lambda is
just another one. So why does the first work, and not the second? What
'black magic' takes place so that int is not mistaken for a method in the
first case?
--
python -c "print ''.join([chr(154 - ord(c)) for c in
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
More information about the Python-list
mailing list