About __class__ of an int literal

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Sep 29 08:07:56 EDT 2010


On Wed, 29 Sep 2010 02:20:55 +0100, MRAB wrote:

> On 29/09/2010 01:19, Terry Reedy wrote:

>> A person using instances of a class should seldom use special names
>> directly. They are, in a sense, implementation details, even if
>> documented. The idiom "if __name__ == '__main__':" is an exception.
>>
> __file__ is another exception.


As are __iter__, __next__, __add__, __dict__, and, yes, __class__, to say 
nothing of all the other special methods.

I'm afraid that I have to disagree with Terry here. Double-underscore 
special variables don't start with double underscores because they're 
implementation details, or to indicate that they're private. They are 
reserved names for attributes or methods that have special meaning to 
Python. 

An implementation that didn't use __dict__ for the namespace of an 
ordinary class, or didn't call __add__ for the + operator, would be 
considered to be buggy.

Naturally one has to be careful about the assumptions you make with such 
special methods. You shouldn't assume, for example, that all classes will 
have a __dict__ attribute. If the class has __slots__ defined, it may 
not. But I think that it is safe to assume any object will have a 
__class__ attribute. At least, I'd report it as a bug if I found one that 
didn't.

(This may change in the future. Given type(), and isinstance(), I'm not 
sure what value __class__ adds.)




-- 
Steven



More information about the Python-list mailing list