[Tutor] Good approach regarding classes attributes

Alan Gauld alan.gauld at btinternet.com
Mon Sep 8 07:36:23 CEST 2014


On 08/09/14 03:31, Juan Christian wrote:

> @property
> def steamid(self):
>      return self._steamid

Unless you specifically *need* these fields to be read-only you don't 
need the property declarations.

Just use the _XXX convention to signal that they are *intended*
to be private and allow clients to access them as myuser._persona_name

Also note the underscore. It improves readability to break multi-words 
like that.
For example several others have quoted this as 'person name' rather than 
'persona name' - quite a different concept but hard to spot when all one 
word...

>    File "D:\Documents\HomeBroker\user.py", line 11, in __init__
>      self._avatar = avatar
> AttributeError: can't set attribute

Thats because you set the property name to the field name.
Notice the difference:

@property
def profileurl(self):
return self._profileurl

@property
def _avatar(self):
return self._avatar


The first sets the property to the non-underscore version
The second uses underscore for both property and field name,
thus making the field read-only. Be careful what you wish for...

Another reason to only use properties when you *need* to
make them read only (or to do some processing on reads
or writes)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list