Reputation: 63
I'm trying to understand how descriptors work in python. I got the big picture, but I have problems understanding the @staticmethod decorator.
The code I'm referring to specifically is from the corresponding python doc: https://docs.python.org/3/howto/descriptor.html
class Function(object):
. . .
def __get__(self, obj, objtype=None):
"Simulate func_descr_get() in Objects/funcobject.c"
if obj is None:
return self
return types.MethodType(self, obj)
class StaticMethod(object):
"Emulate PyStaticMethod_Type() in Objects/funcobject.c"
def __init__(self, f):
self.f = f
def __get__(self, obj, objtype=None):
return self.f
My question is: When self.f
is accessed in the last line, doesn't f
get recognized as a descriptor itself (because every function is a non-data descriptor) and thus gets bound to self, which is a StaticMethod object?
Upvotes: 5
Views: 67
Reputation: 41987
Descriptors are class attributes and hence need to be defined at the class level.
The function f
in the last example is an instance attribute, as set inside __init__
by binding to attribute named f
to the input object referred by f
. As it is not a class attribute, it will never be classified as a descriptor.
Now, from the caller's perspective, staticmethod
is a class attribute as it is implemented at the class level e.g. like:
class Foo:
@staticmethod
def bar():
return 10
the decorator is only a syntactic sugar, you can very well write like:
class Foo:
def bar():
return 10
bar = staticmethod(bar)
so it will be treated as a descriptor in this case.
Upvotes: 5