Python getters and setters

Fernando Saldanha fsaldan1 at gmail.com
Sat Aug 17 12:53:07 EDT 2013


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.

Thanks for the help.

FS




More information about the Python-list mailing list