attributes of Python classes

Roy Smith roy at panix.com
Wed Mar 17 19:46:31 EST 2004


In article <4058F086.490C215B at alcyone.com>,
 Erik Max Francis <max at alcyone.com> wrote:

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

I agree that initializing all attributes in __init__ is a good idea.  
Even if you initialize them to None and overwrite them in some other 
method before ever accessing the value, it's still a nice way to help 
soem future reader understand your class better.  If it's a good idea to 
have self-documenting code, I guess it's an even better idea to have 
executable comments :-)



More information about the Python-list mailing list