Python getters and setters

Fernando Saldanha fsaldan1 at gmail.com
Sun Aug 18 01:26:32 EDT 2013


The debate got more interesting than I expected. Without taking sides, I would like to add that perhaps my "length" example was misleading: length is easy to calculate. The information could be hard to extract from the data, either because complex calculations are involved, or because it is not apparent which pieces of information have to be combined. Also, notice that I never stated that the information was in the shape of an attribute.

The comparison below may seem clear cut if the information to be obtained is length but one could arrive at exactly the opposite conclusion by imagining that "length" is hard to calculate or extract. It may be easier and faster to look up a function in an API than figuring out how to do a complex calculation.

Even in the simple case where the information is "length" there may be more than one reasonable definition. For example, when dealing with time series data in matrix form it makes sense to consider the number of rows as the length of the data, but it also makes sense to define length as the number of elements of the matrix. So the word "len" in the first half of the example below could hide different concepts: consistent but misleading. The different methods in the second half could have the virtue of clarifying which concept of length applies in each case.

"# Yes, this is good, consistent design 
len(myrecord.field) 
len(obj.data) 
len(data.value) 
len(collection[key]) 


# No, this is crappy, inconsistent design 
myrecord.field_len() 
obj.data_length() 
data.get_length_of_value() 
collection.key_len(key)"



More information about the Python-list mailing list