简体   繁体   中英

Why an object in python is of type 'instance'?

I have the following code:

>>> class MyClass:
    pass

>>> myObj=MyClass()

>>> type(myObj)
<type 'instance'>     <==== Why it is not type MyClass ?

>>> type(MyClass)
<type 'classobj'>  <=== Why it is not just 'MyClass'?

>>> isinstance(myObj, instance)  <==== Why the 'instance' is not defined?

Traceback (most recent call last):
  File "<pyshell#91>", line 1, in <module>
    isinstance(myObj, instance)
NameError: name 'instance' is not defined

>>> isinstance(myObj, MyClass)
True

>>> myObj.__class__
<class __main__.MyClass at 0x0000000002A44D68> <=== Why different from type(myObj) ?

It seems Python has some extra indirection between a class and its instance type.

I am used to C#. In C#, typeof(MyClass) will just return the MyClass .

Add 1

Below is some comparison between 2.7.6 and 3.4.1.

I am wondering how the == operator is implemented in Python.

在此输入图像描述

This is because you're using old-style classes . Instead of doing:

class MyClass:
    pass

You need to do:

class MyClass(object):
    pass

...in order to use new-style classes. Now, if you do type(myObj) , you get back <class '__main__.MyClass'> as expected.

In fact, one of the major reasons why Python introduced new-style classes was exactly because of the problem you observed:

New-style classes were introduced in Python 2.2 to unify classes and types. A new-style class is neither more nor less than a user-defined type. If x is an instance of a new-style class, then type(x) is typically the same as x.__class__ (although this is not guaranteed - a new-style class instance is permitted to override the value returned for x.__class__ ).

The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model. It also has a number of practical benefits, like the ability to subclass most built-in types, or the introduction of “descriptors”, which enable computed properties.

( source )

This is a bit of a kludge, having to extend object , but thankfully in Python 3, old-style classes were removed altogether so declaring the class using either forms does the same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM