Properties/Decorators [WAS: Can I reference 1 instance of an object by more names ? rephrase]

Diez B. Roggisch deets at nospam.web.de
Wed May 23 10:29:00 EDT 2007


Wildemar Wildenburger wrote:

> Bruno Desthuilliers wrote:
>> here's an example using a property:
>>
>> class cpu_ports(object):
>>     def __init__(self, value=0):
>>         self._d = value
>>     @apply
>>     def value():
>>         def fset(self, value):
>>             print 'vv'
>>             self._d = value
>>         def fget(self):
>>             return self._d
>>         return property(**locals())
>>   
> Wow! I've never seen properties written that way. Kind of takes all the
> mess out of what it usually is. Nice. BUT! I don't quite get the
> @apply-decorator here. The rest I get and so I gather what it is sort of
> kind of supposed to do. I have only found the depricated apply()
> function in the docs (which I also don't quite get just by scanning it).
> Is it that? If yes: How does it work? If not: What's going on there?

It is that very apply.

And apply takes a function as argument + additional arguments, and executes
that function, returning the result of that function-call. It was used
before the 

f(*args, **kwargs)

notation was introduced.

Now what we have here is "value" as function, passed as single argument to
apply (because decorators are just callables), which will invoke "value"
with no arguments. The result of that operation is the property-object,
that thus is returned by apply. And in the end gets assigned to the name
value in the cpu_ports-class.

diez



More information about the Python-list mailing list