Accessors in Python (getters and setters)

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Thu Jul 13 10:40:00 EDT 2006


mystilleef schreef:
> 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. You can make
> them public later if need be. If anyone tells you making attributes
> private/protected is not Pythonic ignore them. You'll thank me when
> your code base grows.
> 2) If a data attribute might likely be an API, think about controlling
> access to via "properties". 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.

Here's what I have learned from this discussion:

1. Give all symbols in your public interface a sensible name.
2. Don't use accessors and mutators for trivial attributes. If needed 
you can always add them later via properties.

You seem to imply that your rule #1 would have prevented the problem 
you're experiencing. After this whole discussion, frankly I still don't 
understand how it would have done that.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Python-list mailing list