[Tutor] R: Re: Re: Re: Class learning

Cameron Simpson cs at zip.com.au
Sat Jan 24 01:37:10 CET 2015


On 23Jan2015 20:37, Alan Gauld <alan.gauld at btinternet.com> wrote:
>On 23/01/15 11:47, jarod_v6 at libero.it wrote:
>>Thanks so much for clear explanation!!! So in this way work .
>>In [38]: Test().x.__name__
>>Out[38]: 'x'
>>The decoratory proprerty dosen't help to create the class in fast way.. When
>>it is advisable use @property?
>
>Very rarely, and mainly when you need to access a number of attributes 
>some of which are pure data and others are derived via a method. You 
>can make the methods look like data by making them properties.
>
>In 18 years of using python I've used @property about 3 or 4 times in
>real projects. [...]

By contrast, I use it a far bit (though still far less than non-property 
methods).  Generally for derived properties which are:

  - cheap to compute i.e. O(1)

  - which I want to abstract from the things from which it is computed,
    so that the user need not know the object internals (which also leaves
    you freer to change those internals later should the need arise)

  - usually represent some property which is stable, such as a size

  - occasionally (much more rarely) a property which is not stable, eg:
      @property
      def active(self):
        return self._users > 0

Here's an example (from real code) where I keep (externally) a dict which maps 
from node keys to nodes, for fast access and to avoid making more than one node 
for the same key.

  class URI_Node(object):

    def __init__(self, method, uri):
      self.method = method
      self.uri = uri

    @property
    def key(self):
      return self.method, self.uri

Here the .key property happens to be a (method, uri) tuple. Might change in the 
future if that is not enough to uniquely identify the node.

Cheers,
Cameron Simpson <cs at zip.com.au>

Surely it was of this place, now Cambridge but formerly known by the name of
Babylon, that the prophet spoke when he said, 'the wild beasts of the desert
shall dwell there, and their houses shall be full of doleful creatures, and
owls shall build there, and satyrs shall dance there.'
        - Thomas Gray (1716-1771)


More information about the Tutor mailing list