我尝试print type (variable)
查看变量是什么类,repl 告诉我:
<type 'instance'>
有没有办法查看变量是如何构造/谁构造的?
这意味着您正在使用旧式类。在新代码中,您的所有类都应继承自object
:
In [3]: class A(object):
...: pass
In [5]: type(A())
Out[5]: __main__.A
您仍然可以通过查看以下内容来获得旧式课程的课程__class__
:
In [1]: class A: pass
In [2]: A().__class__
Out[2]: __main__.A
http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes:
类和实例有两种风格:旧式(或经典)和新式。
直到 Python 2.1,旧式类是用户唯一可用的风格。(旧式)类的概念与类型的概念无关:如果
x
是旧式类的实例,则x.__class__
指定 的类x
,但type(x)
始终是<type 'instance'>
。这反映了这样一个事实,即所有旧式实例,独立于它们的类,都是用一个名为 instance 的内置类型实现的。Python 2.2 中引入了新型类来统一类和类型。新式类既不多也不少于用户定义的类型。if
x
是新式类的实例,则type(x)
通常与 相同x.__class__
(尽管不能保证 - 允许新式类实例覆盖返回的值x.__class__
)。...
For compatibility reasons, classes are still old-style by default. New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the “top-level type” object if no other parent is needed. The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what
type()
returns. Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are “fixes” that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.Old-style classes are removed in Python 3, leaving only the semantics of new-style classes.