Distinguishing between functions and methods in a decorator.
Diez B. Roggisch
deets at nospam.web.de
Thu Feb 7 11:25:36 EST 2008
Berteun Damman wrote:
> Hello,
>
> I was wondering a bit about the differences between methods and
> functions. I have the following:
>
> def wrap(arg):
> print type(arg)
> return arg
>
> class C:
> def f():
> pass
>
> @wrap
> def g():
> pass
>
> def h():
> pass
>
> print type(C.f)
> print type(h)
>
> Which gives the following output:
> <type 'function'>
> <type 'instancemethod'>
> <type 'function'>
>
> The first line is caused by the 'wrap' function of course. I had
> expected the first line to be 'instancemethod' too. So, I would guess,
> these methods of C are first created as functions, and only then become
> methods after they are 'attached' to some classobj. (You can do that
> yourself of course, by saying, for example, C.h = h, then the type of
> C.h is 'instancemethod' too.)
>
> Why does the wrapping occur before the function is 'made' into an
> instancemethod?
Because a decorator could choose to return any function-object as it likes,
see this example:
def bar(self):
print "bar"
def makebar(f):
return bar
class Foo(object):
@makebar
def baz(self):
pass
foo = Foo()
foo.baz()
So you can't decide if a function is an instancemethod until the very last
moment.
Diez
More information about the Python-list
mailing list