static, class and instance methods
Steve D'Aprano
steve+python at pearwood.info
Thu Oct 6 07:31:23 EDT 2016
On Thu, 6 Oct 2016 05:53 pm, ast wrote:
[...]
> * For instance methods, there is no decorator:
>
> def funct2(self, a, b):
> ...
>
> self is automatically filled with the instance when we call
> funct2 from an instance and not filled if funct2 is called from
> a class.
> But there is no decorator, why ? Is python doing the conversion
> of funct2 to a descriptor itself, behind the scene ?
Functions don't need to be decorated because they are already descriptors.
Descriptors have __get__, __set__ or __delete__ methods. In the case of
methods, it is __get__ which does the work. Normally this happens
automatically, but we can do it by hand:
py> class X(object):
... def func(self):
... pass
...
py> x = X()
py> vars(X)['func']
<function X.func at 0xb7b0b80c>
py> vars(X)['func'].__get__(x, X)
<bound method X.func of <__main__.X object at 0xb7b0ad8c>>
py> x.func
<bound method X.func of <__main__.X object at 0xb7b0ad8c>>
> * static methods are decorated too
>
> @staticmethod
> def funct3(a, b):
> ...
>
> The 1st argument is not supposed to be automatically filled
> So what the decorator used for ?
> Just to distinguish funct3 from an instance method ?
Correct.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list