Good Form

bruno de chez modulix en face bruno at modulix.org
Sat Oct 21 23:12:46 CEST 2006


phez.asap at gmail.com a écrit :

> 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

I assume you mean "instance attributes". In Python, "class attributes"
are attributes that belong to the class object itself, and are shared
by all instances.

>being accessable only through methods
> instaed of directly refrenced from the object instence.

C++ have "access restriction" on attributes, which default is
"private". Also, C++ makes a strong distinction between fonctions and
data. Python's object model is very different here:
1/ There's no language-inforced access restriction. Instead, there's a
naming convention stating that names starting with an underscore are
implementation detail - ie : not part of the public interface - and as
such *should* not be accessed by client code.
2/ Since Python is 100% object, functions (and methods) are objects too
- so there's no strong "member variable vs method" distinction : both
are attributes.

> 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.

That's not technically true. *But* since Python has support for
computed attributes, it's quite easy to turn a raw attribute into a
computed one without the client code noticing it. So from a conceptual
POV, you can think of  direct attribute acces as a computed attribute
acces with implicit getter/setter...

> Would you normally write methods to retrive and set your class
> variables or just refrence them directly?

Depends. Languages like C++ or Java not having support for computed
attributes, the tradition is to have a "public methods==behaviour" /
"private data==state" mindset. With Python's support for both computed
attributes and functions as first class objects, thinks are quite
differents. The best approach IMHO is to think in terms of "public
interface vs implementation", and choose to use attribute or method
syntax based on semantic - how it will be effectively implemented being
an orthogonal concern.

To make things short : if it's obviously an attribute (ie : person's
name etc), start by making it a public attribute and access it
directly. If and when you need to control access to this attribute
(either to compute it or make it read-only or whatever), then turn it
into a property (aka computed attribute).




More information about the Python-list mailing list