Handling Property and internal ('__') attribute inheritance and creation

Eric Brunel see.signature at no.spam
Tue Aug 19 05:30:52 EDT 2008


On Fri, 15 Aug 2008 20:02:36 +0200, Rafe <rafesacks at gmail.com> wrote:
[snip]
> 1) 'Declaring' attributes - I always felt it was good code practice to
> declare attributes in a section of the class namespace. I set anything
> that is constant but anything variable is set again  in __init__():
>
> Class A(object):
>     name = "a name"
>     type = "a typee"
>     childobject = None
>
>     def __init__(self, obj):
>         self.childobject = object
>
> This makes it easy to remember and figure out what is in the class.
> Granted there is nothing to enforce this, but that is why I called it
> 'code practice'. Do you agree or is this just extra work?

To add to what others have already said, it is not only 'just extra work',  
it is also quite dangerous. See:

class A(object):
   children = []

Now *all* A instances share the *same* list, as it was defined as a class  
attribute. If you ever forget to set it to something else in __init__,  
you're in for big surprises.

What I'm doing is set all instance attributes right at the beginning of  
the __init__ with a huge comment before them, like:

class A(object):
   def __init__(self):
     ## INSTANCE ATTRIBUTES:
     ## --------------------
     self.children = []

This way, you still can 'figure out what is in the class' quite quickly,  
without the drawbacks of declaraing class attributes.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"



More information about the Python-list mailing list