Pseudo-Private Class Attributes

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Sep 19 03:59:52 EDT 2007


Ricardo Aráoz a écrit :
> That is self.__attributes
> 
> Been reading about the reasons to introduce them and am a little
> concerned. As far as I understand it if you have a class that inherits
> from two other classes which have both the same name for an attribute
> then you will have a name clash because all instance attributes "wind up
> in the single instance object at the bottom of the class tree".
> 
> Now I guess this means that in any real OOP project you'd better use
> __attr for all your attributes, because classes are usually meant to be
> subclassed and you can never know when you'll be subclassing from two
> classes with attributes with the same name, and I guess you can't take
> the risk of this happening because when it happens it will be hell to
> find out what's going on.
> 
> Is this right?

Wild guess : you're coming from Java or C++ ?-)

I don't know for sure what you mean by "real OOP project", but any 
non-trivial Python project surely qualifies IMHO, and it seems that so 
far no one had too much problem with this, so you're perhaps needlessly 
worrying.

Note that given Python's type system, inheritence is mostly about 
implementation - you don't need it for polymorphic dispatch. This 
results in class hierarchies being way much flatter in Python than in 
languages with declarative static typing - IOW, Python's classes are not 
necessarily "meant to be subclassed".

Also, while Python does support multiple inheritance, it's rarely used 
in practice (except perhaps in Zope 2, which is that pythonic). Python 
has great support for delegation, so composition/delegation is often 
used where MI would have been used in C++.

FWIW, __private names are of very rare use in Python. As far as I'm 
concerned, I must have use this feature a couple of times at most, in 
base classes or metaclasses of a small framework, because these couple 
attributes where really vital to the sytem and should by no mean be 
overloaded.

My 2 cents.




More information about the Python-list mailing list