Op 07-04-16 om 00:03 schreef Marko Rauhamaa:
Once you look up an object method, it doesn't have a self argument. The
self argument is cooked up for the benefit of the function definition in
the class.
IOW, if I have this class:
class A:
def f(self):
print("f")
and this object:
a = A()
then,
a.f
is a function that doesn't have a self argument. That function is
generated on the fly, and it delegates to A.f, providing it with self
argument.
a.f is not a function, A.f is a function.
a.f is an instance method. The function is not generated on the fly,
when the method is called, it calls the function A.f with an extra
argument __self__ (the instance a) inserted before the argument list the
instance method was called with.
So calling a.f() is a convenient way to write A.f(a)
However, a.f itself is just a function that doesn't accept any
arguments.
As i wrote, a.f is an instance method not a function. It accepts any
argument you trow at it, insert 'a' in front of the argument list and
calls the function A.f with this new argument list.
Defining:
def f():
print("f")
a.f = f
simply short-circuits the attribute lookup process; no need to consult
the class when the attribute (method!) is right there in the object's
dict.
Here a.f is a function so Python will treat is as a function. When you
call it, the lookup process will find f in the class instance
dictionary, discover it's a function and run it with the arguments
provided. If you would like to use attributes of the class A or of the
instance 'a' in f, you would need to hard code it in the function since
the function f does not know it was called from 'a', an instance of the
class A.
Marko
--
https://mail.python.org/mailman/listinfo/python-list