[Tutor] Properties of an object

Jervis Whitley jervisau at gmail.com
Fri Jan 30 00:50:29 CET 2009


>
>
>
> For me, the "()" look like artificial, not necessary. I would prefer just
> to type    "a.list_1stpart"   , a property.
>
>
>
> --
>
> Others have explained their preference for using get methods for accessing
internal data structures, However it does look like you have specifically
mentioned a preference for attribute like access:

e = ExampleList([1,2,3,4], 2)
>>> e.firstpart
[1,2]

rather than
>>> e.firstpart()
[1,2]

We can implement this using properties, and I will refer you to some of the
documentation http://docs.python.org/library/functions.html#property

Here is just one way that you could simply implement a property in your
case:

class ExampleList(object):
   """Note that this is a new style class."""
   def __init__(self, sequence, position):
      self._sequence = sequence
      self._position = position
   @property
   def firstpart(self):
      """This method will be called on inst.firstpart rather than
inst.firstpart()."""
      return self._sequence[:self._position]

Here I have used property as a decorator (described in the link), now you
can get your
firstpart through attribute access (not that you cannot 'set' to it):

e.firstpart

Cheers,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090130/fcc54911/attachment.htm>


More information about the Tutor mailing list