ClassName.attribute vs self.__class__.attribute

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Thu Jun 5 15:44:43 EDT 2008


On 5 juin, 17:40, Gabriel Rossetti <gabriel.rosse... at arimaz.com>
wrote:
> Hello everyone,
>
> I had read somewhere that it is preferred to use
> self.__class__.attribute over ClassName.attribute to access class (aka
> static) attributes.

It's even prefered to use self.attribute, unless you know you have
both an instance and a class attribute by the same name (but then if
you need to know which one you're accessing then you have a serious
design problem).

> I had done this and it seamed to work, until I
> subclassed a class using this technique and from there on things started
> screwing up. I finally tracked it down to self.__class__.attribute! What
> was happening is that the child classes each over-rode the class
> attribute at their level,

Which is why it's prefered to access the attribute from the class (or
more simply from the instance which will get them from the class) - a
subclass may have extremly good reasons to have it's own instance of
the attribute.

> and the parent's was never set,

This is another problem.

> so while I was
> thinking that I had indeed a class attribute set in the parent, it was
> the child's that was set, and every child had it's own instance! Since
> it was a locking mechanism, lots of fun to debug...

I can well believe it, and you do have my whole sympathy.

> So, I suggest never
> using self.__class__.attribute, unless you don't mind it's children
> overriding it, but if you want a truly top-level class attribute, use
> ClassName.attribute everywhere!

I would not have expressed it that way. My own experience is that,
most of the time, you do know when it's ok for the subclasses to have
their own instance of the attribute and when it's not, so in the (very
rare) cases it's not ok you use __name_mangling.

Now I'd say that *unknowingly* overriding an attribute of your own
base class when you didn't expect it to happen is mostly a sign that
there's something you don't (didn't ?) quite get wrt/ lookup  /
assignment  / namespace etc rules in Python.

> I wish books and tutorials mentioned this explicitly....

Possibly. OTHO, if you understand Python's lookup (name resolution)
rules, the difference between MyBaseClass.attrib and
self.__class__.attrib should be obvious. But this surely could be a
good example in a tutorial !-)



More information about the Python-list mailing list