A matter of style: class.foo = bar vs. class.set_foo(bar)

echuck at mindspring.com echuck at mindspring.com
Sat Nov 11 10:43:57 EST 2000


In article <8uhkk9$2r5$1 at panix2.panix.com>,
  aahz at panix.com (Aahz Maruch) wrote:
> In article <slrn90okck.ilq.grey at teleute.rpglink.com>,
> Steve Lamb <morpheus at here.not.there> wrote:
> >
> >OK, when setting a variable from program logic is it acceptable to
set it
> >directly or should one create a method to set the variable?
>
> Generally speaking, because Python does not have private parts, you
only
> use a method when you want to trigger an action in addition to just
> changing the variable's value.
> --
>                       --- Aahz (Copyright 2000 by aahz at pobox.com)
>

But you can do the setFoo() if you like.

The disadvantage of:
  obj.foo = 5

is that in the future if you want to take some action when foo is set,
like asserting that it's in range or not None, then you're out of luck.
With setFoo() you can change the underlying semantics with minimal
chance of breaking the code that uses the object.

So I do things like this:

  def setFoo(self, foo):
    assert foo is not None
    assert foo>0
    self._foo = foo


-Chuck
--
Webware for Python:
http://webware.sourceforge.net


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list