attributes of Python classes

Yermat loic at
Thu Mar 18 09:27:07 CET 2004

Roy Smith a écrit :
> In article <4058F086.490C215B at>,
>  Erik Max Francis <max at> wrote:
>>beliavsky at 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
>>>    __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 :-)

I agree BUT there is 2 cases were I don't follow this rules :

1) I have a project that creates a lot of objects by reading a file. The 
time is twice as needed if I initialize first the attribute and then set 
them from the values given by the file...

2) When using an algorithm that need to decorate the object, it's easier 
to just add attribute to the object rather than create a dictionnary or 
something like that.

But for te sake of documentation, your rules sound good to me. For the 
first problem, I don't know how to solve it nicely.

The second is not a problem because, the algorithm know what he's doing.


More information about the Python-list mailing list