Python type() or __class__, == or is

For old-style classes, there is a difference:

>>> class X: pass
... 
>>> type(X)
<type 'classobj'>
>>> X.__class__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class X has no attribute '__class__'
>>> x = X()
>>> x.__class__
<class __main__.X at 0x171b5d50>
>>> type(x)
<type 'instance'>

The point of new-style classes was to unify class and type. Technically speaking, __class__ is the only solution that will work both for new and old-style class instances, but it will also throw an exception on old-style class objects themselves. You can call type() on any object, but not every object has __class__. Also, you can muck with __class__ in a way you can’t muck with type().

>>> class Z(object):
...     def __getattribute__(self, name):
...             return "ham"
... 
>>> z = Z()
>>> z.__class__
'ham'
>>> type(z)
<class '__main__.Z'>

Personally, I usually have an environment with new-style classes only, and as a matter of style prefer to use type() as I generally prefer built-in functions when they exist to using magic attributes. For example, I would also prefer bool(x) to x.__nonzero__().

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)