Defining accessor methods

Roman Suzi rnd at onego.ru
Tue Jun 26 00:58:10 EDT 2001


On Tue, 26 Jun 2001, Greg Ewing wrote:

>Since getting attributes tends to be more common than
>setting them, this isn't unbearably verbose, and I find
>that having 'set' in the setting method's name helps to
>make the code read more explicitly.
>
>> I've not noticed any use of accessor methods in sample Python code
>> (i.e. in books/tutorials); do people use them much in Python?
>
>I make extensive use of them in the API of my Python GUI
>project (http://www.cosc.canterbury.ac.nz/~greg/python_gui/).
>I want the API to be as future-proof as possible, so all
>publically-visible attributes of my GUI objects are accessed
>through methods. I use the convention I recommended above,
>plus a couple of others. One is that the constructors of
>my objects allow initial values to be given for all its
>attributes using keyword arguments, so that e.g.
>
>  b = Button(width = 42, height = 17, text = "Boo!")
>
>is equivalent to
>
>  b = Button()
>  b.set_width(42)
>  b.set_height(17)
>  b.set_text("Boo!")

Greg, I am not convinced that set_* methods are good.
In Python standard library (/usr/lib/python2.1/*.py part of it):
set_* is used 54 times in 18 files. WHile there are
~ 343  classes in 101 file.

set_* deviates slightly from being Python idiom.

In Python

[=] ... b.width   # is get
b.width =         # is set
del b.width       # is del

Of course, there is no need to define self.width by hand,
__setattr__ could catch _both_ forms and do set_attr as
well as attr.

>My objects also have a set() method which takes keyword
>arguments in the same way, so if you want to change a
>bunch of attributes you can set them all in one go with
>a statement like
>
>  b.set(width = 200, text = "Start Spanish Inquisition")

This is better.
Then no individual set_ are needed, because
they aren't syntactically scalable, while set() is:

b.set(
  width = 200,
  text = "Start Spanish Inquisition",
)

could be later extended by adding only essentials:

b.set(
  width = 200,
  height = 40,
  text = "Start Spanish Inquisition",
)

(please not ',' after each parameter)

>These two things help to cut down a lot on the verbosity
>of using set_xxx methods.


Sincerely yours, Roman Suzi
-- 
_/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/
_/ Tuesday, June 26, 2001 _/ Powered by Linux RedHat 6.2 _/
_/ "It is better to be brief than boring." _/





More information about the Python-list mailing list