[Tutor] Python property()

Alan Gauld alan.gauld at btinternet.com
Sun May 17 01:27:56 CEST 2015


On 16/05/15 20:25, daaku gee wrote:

> I think I understand what's going on here.  What I don't understand is
> if/when to use property instead of a normal attribute.
>
> 1. Is 'property' used widely? Do you use it?

No,
Yes, occasionally

I first came across properties in Borland Delphi (Object Pascal)
and found them useful there because there was quite a bit of
emphasis on data hiding.

After I moved to Python which has a much more open approach
to data I find them less useful.

> 2. Would you use it only when you need to validate or calculate the value
> to be assigned to an attribute or is there any other place for 'property()'
> to be used?

Those are the main use cases for me.
Calculating values can be an important one though,
especially if it avoids the need for lots of methods
to update some attribute like size. You can calculate
it at runtime and expose the method to look like a
data item.

But that in itself can be done by a method,
the real driver to a property is when I'm using the
class in a polymorphic relationship with other classes
that do have a data attribute and I want mixed access
with a common interface.

> 3. If there is value in learning and using property, kindly explain it or
> point me to a document/writeup/book that I should read to get a better
> understanding.

Oddly enough I'm currently reviewing a book that addresses
this quite well in a chapter on properties. But it won't
be published till later in the year so not much help to
you just now.

Personally I wouldn't worry about them until you think you've
found a real use for them. There are plenty other things to
be doing first!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list