Good Form

Travis Vachon tvachon at gmail.com
Sat Oct 21 10:58:23 CEST 2006


Hi Phez

Generally, most Python programmers I know access and set class 
attributes directly. This is done because of a Python feature called 
property().

In many languages, setting class attributes directly is discouraged 
because additional behavior may need to be associated with that setting, 
and it may be difficult or impossible to later inject this behavior into 
the setting action.

In Python, however, if we have a class like

class A:
    a = 1
   
we just get and set a like:

 >>> obj = A()
 >>> obj.a = 2

If we later want to associate additional behavior with setting A.a, we 
can do the following:

class A(object):
    _a = 1
    def _get_a(self):
          additional_action()
          return self._a
    def _set_a(self, val):
          some_other_additional_action()
          _a = val
    a = property(_get_a, _set_a)

Now when we do

 >>> obj = A()
 >>> obj.a = 2

obj.a = 2 will call _set_a(self, 2), which in this case will run 
some_other_additional_action() and then set a to 2.

Gregor's post contains prudent advice on when to use this property() 
business (that is, only when definitely needed :) ).

Best,

Travis Vachon


phez.asap at gmail.com wrote:
> I am new to Python but come from a C++ background so I am trying to
> connect the dots :) . I am really liking what I see so far but have
> some nubee questions on what is considered good form. For one thing I
> am used to class variables being accessable only through methods
> instaed of directly refrenced from the object instence. From what I
> have read it looks like when you access a class variable directly in
> Python it has something in the background that works similar to a
> getter of setter.
>
> Would you normally write methods to retrive and set your class
> variables or just refrence them directly?
>
>   




More information about the Python-list mailing list