Named integers and enums
Steve Holden
sholden at holdenweb.com
Tue May 25 19:20:12 EDT 2004
Hallvard B Furuseth wrote:
> Scott David Daniels wrote:
>
>>Hallvard B Furuseth wrote:
>>
>>
>>>I wonder: isinstance() says that even classic class instances are 'object'
>>>instances, even though they do not seem to be (since __slots__ does not
>>>work):
>>> >>> class o: __slots__ = ()
>>> ...
>>> >>> isinstance(o(), object)
>>> 1
>>> >>> o().foo = True
>>> >>>
>>
>>Actually __slots__ works, you just have a funny idea of what __slots__
>>is _for_. __slots__ is a _storage_optimization_.
>
>
> That's not what I mean.
>
> I'm wondering why isinstance() claims that instances of 'o' are
> instances of 'object', when 'o' is not declared to be a subclass of
> 'object'.
>
Instances of o are instances of object because, I believe, everything is
ultimately held to be an instance of object. Unless you can find an x
such that
isinstance(x, object)
is false - I couldn't find such a value.
> I used __slots__ to check if 'o' is a subclass of 'object' anyway, since
> __slots__ is documented to only work for new-style classes - i.e.
> classes derived from 'object'. Well, it is not. If it had been, the
> assignment to o().foo above would have failed.
>
As you appear to have deduced, the purpose of __slots__ is to limit the
keys that can be stored in the object's __dict__, and so clearly o is
not a subclass of object. But you could have determined that directly:
>>> class o: pass
...
>>> issubclass(o, object)
False
>>> issubclass(int, object)
True
However, none of this tells you anything about the relationship between
object, old-style class and instances thereof:
>>> type(o)
<type 'classobj'>
>>> oi = O()
>>> type(oi)
<type 'instance'>
>>> issubclass(oi, object)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: issubclass() arg 1 must be a class
Sometimes it's difficult to keep your head from exploding:
>>> type(object)
<type 'type'>
>>> type(type)
<type 'type'>
regards
Steve
More information about the Python-list
mailing list