ClassName.attribute vs self.__class__.attribute

Hrvoje Niksic hniksic at xemacs.org
Thu Jun 12 10:19:16 CEST 2008


Mike Orr <sluggoster at gmail.com> writes:

> There's a very good reason to use self.__class__: it makes it
> possible to subclass your class.

This really depends on the usage.  In the OP's use case, he wanted the
subclasses to share the same lock object defined in the superclass
(because of synchronization), so it would have been wrong to use
self.__class__ *because* of subclassing.

Also note that for new-style classes, self.__class__ can be spelled as
type(self), since there is no distinction between classes and types.

> It's a little annoying that if you want to print a class's name in
> some unknown object, you have to use obj.__class__.__name__ if it's
> an instance, and obj.__name__ if it's a class.  I sometimes wish
> classes had a .__class__ attribute that's the class itself, but I
> can see how that would cause its own confusion (and recursion).

They do, the metaclass.  :-)



More information about the Python-list mailing list