About __class__ of an int literal

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Thu Sep 30 03:21:38 CEST 2010


On Wed, 29 Sep 2010 14:34:33 +0200, Hrvoje Niksic wrote:

> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
>> (This may change in the future. Given type(), and isinstance(), I'm not
>> sure what value __class__ adds.)
> 
> None whatsoever.  __class__ used to be necessary to tell the appart
> instances of different old-style classes:
> 
>>>> class X: pass  # old-style
> ...
>>>> X().__class__
> <class __main__.X at 0xb772f2fc>
>>>> type(X())
> <type 'instance'>
> 
> Now that classes produce real types, they are equivalent.


I've been thinking about this, and I think that there may be a use-case 
for changing __class__ manually. I'm not entirely sure if this is a good 
idea or not, I'd need to spend some time experimenting, but imagine a 
class that wraps another object and uses delegation instead of 
inheritance.

If you also set __class__ (on the class itself, naturally, not the 
instance) appropriately, then type(instance) and instance.__class__ will 
be different. type() will return the "real" type of the delegation class, 
while instance.__class__ returns the class that it is trying to be.

And of course, presumably metaclasses can do anything they like with 
__class__, for good or ill.

I'm not sure if and when this would be useful, but it's a hint that 
perhaps the distinction is not entirely meaningless.



-- 
Steven



More information about the Python-list mailing list