By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,001 Members | 1,262 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,001 IT Pros & Developers. It's quick & easy.

Re: ClassName.attribute vs self.__class__.attribute

P: n/a

"Casey McGinty" <ca***********@gmail.comwrote in message
| On Thu, Jun 5, 2008 at 5:40 AM, Gabriel Rossetti <
| ga**************@arimaz.comwrote:
| Hello everyone,
| >
| I had read somewhere that it is preferred to use
| over ClassName.attribute to access class (aka static) attributes. I had
| this and it seamed to work, until I subclassed a class using this
| and from there on things started screwing up. I finally tracked it down
| self.__class__.attribute! What was happening is that the child classes
| over-rode the class attribute at their level, and the parent's was
| set, so while I was thinking that I had indeed a class attribute set in
| 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... So,
| suggest never using self.__class__.attribute, unless you don't mind
| children overriding it, but if you want a truly top-level class
| use ClassName.attribute everywhere!
| Thanks for the info. Can anyone explain more about the differences
| the two techniques? Why does one work and the other one fail?

If you want to access the attribute of a particular class, to read or
write, use that class.
Note that no instance is required or relevant.

If you want to read the attrubute of the class of an instance (or the first
superclass with the attribute, whatever that class might be, use self.attr
or self.__class__.attr. (Use the latter if the instance has (or might
have) an attribute of the same name).

For setting an attribute, self.attr = x sets it on the instance while
self.__class__.attr = x sets it on its class.

Jun 27 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.