Python getters and setters

Irmen de Jong irmen.NOSPAM at xs4all.nl
Sat Aug 17 18:52:06 EDT 2013


On 17-8-2013 19:18, Steven D'Aprano wrote:
> On Sat, 17 Aug 2013 09:53:07 -0700, Fernando Saldanha wrote:
> 
>> Suppose my class contains an attribute called "data" that can
>> potentially provide a lot of information that will be needed by class
>> users. I have two options:
>>
>> 1) For each piece of information within data (e.g., length) I write a
>> method that retrieves that information:
>>
>>     def data_length(self):
>>         return len(self.data)
> 
> Certainly not. Python is not Java.
> 
> 
>> 2) I do not create such a method. Users that are interested in that
>> information will have to write len(obj.data), where obj is a previously
>> instantiated object of my class.
> 
> This one.
> 
> 
>> Which one of the two alternatives fits better with the Python
>> philosophy? The first alternative is more work for me, creates a
>> "heavier" class and may have slower performance, but makes things easier
>> for the user and is more implementation independent.
> 
> How is this:
> 
> obj.data_length()
> 
> easier for the user than this?
> 
> len(obj.data)
> 

It's not easier for the user perse, but it might be preferable from a design point of
view. For the direct components of obj, it's probably alright to access them directly.
There's something called the Law of Demeter aka principle of least knowledge
(http://en.wikipedia.org/wiki/Law_of_Demeter) though. It basically argues against the
use of "more than one dot". Doing that ties the use of the object more to the actual
implementation/internal structure of the object.


Irmen




More information about the Python-list mailing list