attributes of Python classes

Erik Max Francis max at alcyone.com
Wed Mar 17 19:42:46 EST 2004


beliavsky at aol.com wrote:

> I have started using classes with Python and have a question
> about their use.
> 
> In Python, 'attributes are all "public" and "virtual" in C++
> terms; they're all accessible everywhere and all looked up
> dynamically at runtime' (Quoting "Learning Python", 2nd. ed.,
> p367). It seems to me that two good conventions are to
> 
> (1) initialize all attributes in the __init__ function
> (2) avoid creating new attributes elsewhere that are not initialized
> in
>     __init__
> 
> I have not followed these conventions so far, and sometimes
> it is difficult for me to tell what attributes an instance of
> a class has. Are these conventions good?

Yes, I think so, provided a key feature of the class in question isn't
that it's inherently dynamic (in which case it's inherently infeasible
to do this) -- an example might be a class that you'd like to mimic the
interface of a module, so it effectively acts like a dictionary but it
allows attribute access to access the dictionary as well.

I certainly follow them as best as is possible in my own code; I can
only think of once instance in an old project where I don't do that, and
it's marked as ugly in the code.

-- 
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ Everyone wants to look good at his own funeral.
    -- Louis Wu



More information about the Python-list mailing list