Getters and setters in python, common practise

Jack Diederich jack at performancedrivers.com
Fri Apr 16 18:48:49 EDT 2004


On Thu, Apr 15, 2004 at 10:25:07AM +0200, Max M wrote:
> Petter Holmstr?m wrote:
> 
> >Hello,
> >
> >Having a Delphi/Object Pascal-background, I'm very used to using getters 
> >and setters when designing my classes. What is the common practise in 
> >the Python world? Should one use them or not?
> 
> Start with simple object attributes, then convert to attribute functions 
>  using get/set-ers when needed.
> 
Agreed, do a search on some keywords plus "considered (evil|harmful)"

I consider get/set harmful 99% of the time, so read the rest of this
post as opinion.

Getter/Setters seem object oriented, but they usually aren't.
You are hiding nothing, you aren't abstacting anything either.
Someone is still depending on accessing a very particular attribute of 
your class.  If the same amount of code has to be changed when you
alter a getset method as when you alter a member your getset
methods are just adding obscurity and call overhead with no reward.

The object you are calling should get its state explicitly passed in
during __init__, and if it needs something else it should be passed in
on a method call.  get/set methods are typically an indication that an
instance is 'peeking' at something else to figure out what to do.

Make "grep counts" your mantra.  Passing things only at the time they
are actually needed makes things obvious.

import amodule
def myfunc(self):
  # obvious, only gets what it needs.
  amodule.launch_debugger(use_globals=self.vars)

import amodule
def myfunc(self):
  # has to get 'vars' from self, might silently grow to do evil later.
  amodule.launch_debugger(self)

If you limit what methods can use to what they are explicitly given it
also makes writing unit tests much, much easier.

-jackdied


 




More information about the Python-list mailing list