On 17/08/2013 17:53, Fernando Saldanha wrote:
I am new to Python.
I understand that it is "unpythonic" to write getters and setters, and that
property() can be used if necessary.
This deals with the case of attributes, but there are other kinds of
information available within a class.
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)
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.
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.
If the attribute is public, i.e. the user is expected to write obj.data,
then
len(obj.data) is the right way to get its length.
--
http://mail.python.org/mailman/listinfo/python-list