osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

type and object


On Fri, 6 Oct 2017 03:17 am, Naveen Yadav wrote:

> Hi folks,
> 
> 
>>> isinstance(type, object) is True   # 1
> and
>>> isinstance(object, type) is True   # 2
> 
> 
> its means type is object is type, But i am not sure how is this.

No. type and object are not the same thing:


py> type is object
False
py> id(type), id(object)
(2, 3)

(You may get different numbers if you call id() on your system. Remember that
id() returns an opaque ID number. What matters is that they are different,
not the specific values.)

> For what i can understand is
> for #1: since every thing is object in python, type is also an object.

Correct. type is an instance of object:

py> isinstance(type, object)
True

But type is also a subclass of object:

py> issubclass(type, object)
True

That means if we ask type what its superclasses are, object will be included
in the list of parent classes (superclasses):

py> type.__mro__
(<type 'type'>, <type 'object'>)


> and
> for #2: object is a base type. therefore object is type

No. That doesn't mean that object is type. It just means all objects inherit
from object, including type.

type and object are special, because object is also an instance of type!

py> isinstance(type, object)
True
py> isinstance(object, type)
True

So which came first? If type is an instance of object, then object must have
came first; but if object is an instance of type, then type must have come
first. Paradox!

The answer to this paradox is that type is special, and the Python interpreter
creates type before anything else. Once type is boot-strapped, then object
can be created, and then type can be turned into an object instance. All the
magic happens inside the interpreter.

This is one of the more brain-melting parts of Python, but don't worry about
it. In practice, you almost never need to care about it.



-- 
Steve
?Cheer up,? they said, ?things could be worse.? So I cheered up, and sure
enough, things got worse.