Why is an object in python an instance type?

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) ?

Python seems to have some additional designation between a class and its instance type.

I am using C #. In C #, typeof(MyClass)it will just return MyClass.

Add 1

The following is a comparison between 2.7.6 and 3.4.1.

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

enter image description here

+4
source share
1 answer

This is because you are using old-style classes . Instead of this:

class MyClass:
    pass

You need to do:

class MyClass(object):
    pass

... to use the new style classes. Now, if you do type(myObj), you are returning <class '__main__.MyClass'>as expected.

, , Python , - , :

Python 2.2 . . x , type(x) x.__class__ ( - , x.__class__).

. , "", .

()

kludge, object, , , Python 3 , .

+8

All Articles