Reputation: 15793
I try print type (variable)
to see what class is the variable, and the repl tells me:
<type 'instance'>
Is there a way to see how was constructed/ who constructed the variable ?
Upvotes: 0
Views: 675
Reputation: 62888
That means you are using old-style classes. In new code, all your classes should inherit from object
:
In [3]: class A(object):
...: pass
In [5]: type(A())
Out[5]: __main__.A
You can still get the class of an old-style class by looking at __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:
Classes and instances come in two flavors: old-style (or classic) and new-style.
Up to Python 2.1, old-style classes were the only flavour available to the user. The concept of (old-style) class is unrelated to the concept of type: if
x
is an instance of an old-style class, thenx.__class__
designates the class ofx
, buttype(x)
is always<type 'instance'>
. This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.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, thentype(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__
)....
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.
Upvotes: 7