newb question about @property

Chris Angelico rosuav at gmail.com
Sun Oct 1 18:59:18 EDT 2017


On Mon, Oct 2, 2017 at 9:47 AM, Bill <BILL_NOSPAM at whoknows.net> wrote:
> Stephan Houben wrote:
>>
>> Op 2017-10-01, Bill schreef <BILL_NOSPAM at whoknows.net>:
>>>
>>> I watched an example on YouTube where someone wrote a simple descriptor
>>> ("@Time_it) to output the amount of time that it took ordinary functions
>>> to complete.    To be honest, I AM interested in descriptors.
>>
>> Are you sure you are not confusing deSCRIPTtors and deCORAtors here?
>
>
> Yet, you are absolutely correct!  Thank you for clarifying! From your
> description, I can see that it was *decorators*, which drew my interest.  It
> appears that *property* is perhaps both a decorator and a descriptor, at
> least when used as in the examples we have been discussing.

Yes, that's correct. The *descriptor* protocol is what allows
"foo.bar" to cause a function to be executed; the *decorator* protocol
is what lets you "tag" a function:

class Foo:
    @property # this is being used as a decorator
    def bar(self):
        return 42

foo = Foo(); print(foo.bar) # this uses descriptor protocol to find the function

Decorators are fairly straight-forward if you understand higher-order
functions. If you DON'T understand higher-order functions, look those
up first and get a solid understanding of what it means to pass a
function as a parameter to another function.

ChrisA



More information about the Python-list mailing list