Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #52636
| Date | 2013-08-17 18:10 +0100 |
|---|---|
| From | MRAB <python@mrabarnett.plus.com> |
| Subject | Re: Python getters and setters |
| References | <227bd47c-0e86-4d65-985f-e59aa4f25294@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.17.1376759432.23369.python-list@python.org> (permalink) |
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.
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Python getters and setters Fernando Saldanha <fsaldan1@gmail.com> - 2013-08-17 09:53 -0700
Re: Python getters and setters MRAB <python@mrabarnett.plus.com> - 2013-08-17 18:10 +0100
Re: Python getters and setters Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-08-17 17:18 +0000
Re: Python getters and setters Tim Chase <python.list@tim.thechases.com> - 2013-08-17 12:31 -0500
Re: Python getters and setters Irmen de Jong <irmen.NOSPAM@xs4all.nl> - 2013-08-18 00:52 +0200
Re: Python getters and setters Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-08-17 23:40 +0000
Re: Python getters and setters Chris Angelico <rosuav@gmail.com> - 2013-08-18 02:07 +0100
Re: Python getters and setters Fernando Saldanha <fsaldan1@gmail.com> - 2013-08-17 22:26 -0700
csiph-web