Python getters and setters
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Aug 17 13:18:08 EDT 2013
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)
The second is shorter to type, and it is a standard idiom that works
everywhere. You want to know the length of something? len(something), no
matter what it is. You don't have to play a game of "Guess the method
name" with every class you come across.
# 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)
--
Steven
More information about the Python-list
mailing list