type versus __class__

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jan 15 02:26:00 CET 2015

There are (at least) two ways to determine the type of something in Python:



By design, they are not guaranteed to give the same result. Is there a
definitive explanation given by the docs for the difference and which you
should use under different circumstances?

In Python 2, the type() of classic classes is always the same thing:

py> class A:  # classic class
...     def spam(self): return "from A"
py> class B:
...     def spam(self): return "from B"
py> a = A()
py> b = B()
py> a.__class__ is b.__class__
py> type(a) is type(b)  # a special type "instance"

Writing to __class__ lets you modify the behaviour of the instance:

py> a.spam()
'from A'
py> a.__class__ = B
py> a.spam()
'from B'

New-style classes are different:

py> class C(object):  # new-style class
...     def spam(self):
...             return "from C"
py> class D(object):
...     def spam(self):
...             return "from D"
py> c = C()
py> d = D()
py> c.__class__ is d.__class__
py> type(c) is type(d)

Like classic classes, you can override the __class__ attribute on instances,
and change their behaviour:

py> c.spam()
'from C'
py> c.__class__ = D
py> c.spam()
'from D'

Any other differences? 


More information about the Python-list mailing list