[英]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. 似乎Python在类和它的实例类型之间有一些额外的间接 。
I am used to C#. 我习惯了C#。 In C#, typeof(MyClass)
will just return the MyClass
. 在C#中, typeof(MyClass)
将返回MyClass
。
Below is some comparison between 2.7.6 and 3.4.1. 以下是2.7.6和3.4.1之间的一些比较。
I am wondering how the ==
operator is implemented in Python. 我想知道如何在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. 现在,如果你type(myObj)
,你会按预期返回<class '__main__.MyClass'>
。
In fact, one of the major reasons why Python introduced new-style classes was exactly because of the problem you observed: 事实上,Python引入新式类的主要原因之一正是由于您观察到的问题:
New-style classes were introduced in Python 2.2 to unify classes and types. Python 2.2中引入了新式类来统一类和类型。 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 asx.__class__
(although this is not guaranteed - a new-style class instance is permitted to override the value returned forx.__class__
). 如果x是新样式类的实例,则type(x)
通常与x.__class__
相同(虽然这不能保证 - 允许新样式类实例覆盖为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. 它还具有许多实际的好处,例如能够对大多数内置类型进行子类化,或者引入“描述符”,它们可以启用计算属性。
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. 这有点像kludge,不得不扩展object
,但幸运的是在Python 3中,旧式类被完全删除,因此使用任一种形式声明类都做同样的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.