Accessors in Python (getters and setters)

Bruno Desthuilliers onurb at xiludom.gro
Thu Jul 13 11:04:24 EDT 2006


mystilleef wrote:
> Ant wrote:
> 
>>We seem to be flogging a dead horse now. Is the following a fair
>>summary:
>>
>>Q. What is the Pythonic way of implementing getters and setters?
>>
>>A. Use attributes.
>>
>>Quote: "I put a lot more effort into choosing method and function
>>names"
>>
>>Wisdom: Python is a different paradigm from (e.g.) Java w.r.t.
>>accessors: Put the effort you would have put into choosing accessor
>>names into choosing attribute names.
>>
>>Anything else to add to this? Or can it be put to bed?
> 
> 
> Here are the lessons I've learned (the hard way).
> 
> 1) Make all attributes of a class private or protected. 

Unless they are obviously part of the implementation (ie: when you would
definitively had written getters/setters in Java), in which case make
them public (and name them with the same care you would have for Java
getters/setters). You can change the implementation later.

> You can make
> them public later if need be. If anyone tells you making attributes
> private/protected is not Pythonic ignore them.

Don't. Just make sure you have the right *API*.

> You'll thank me when
> your code base grows.

Unless everybody ditch your code and roll their own because they are
bored with coding Java in Python.

> 2) If a data attribute might likely be an API, think about controlling
> access to via "properties". 

If you need to control anything - else just use a plain attribute.

> That's the pythonic way to implement
> accessors and mutators
> 
> I guess people who've done medium to large scale programming in Python
> already know this.

Do 50+ KLOC count as "medium to large scale" here ?

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list