Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52635

Python getters and setters

Newsgroups comp.lang.python
Date 2013-08-17 09:53 -0700
Message-ID <227bd47c-0e86-4d65-985f-e59aa4f25294@googlegroups.com> (permalink)
Subject Python getters and setters
From Fernando Saldanha <fsaldan1@gmail.com>

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


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