liveBook · Manning

__class__ attribute

As explained in The Quick Python Book, Fourth Edition

The __class__ attribute references the class object associated with a Python object.

An instance’s __class__ attribute references the class object that created it. For an instance b of B, b.__class__ produces the same class object as type(b), which can then be stored, compared, or passed like any other Python object. section 17.3

Use the retrieved class object to inspect its identity and inheritance:

  • __name__ returns the class name, such as 'B'. section 17.3
  • __bases__ returns a tuple containing the class’s direct base classes. section 17.3
  • isinstance() and issubclass() usually provide more user-friendly checks when the goal is type or inheritance testing. section 17.3

Comparing __class__ with type()

class A: pass class B(A): pass b = B() b.__class__ == B # True type(b) == b.__class__ # True b.__class__.__name__ # 'B' b.__class__.__bases__ # (A,) section 17.3

b.__class__
<class '__main__.B'>

Inspect the class associated with an instance directly, then use the resulting class object for further queries. section 17.3

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains equivalent access through type(), then follows the class object to __name__ and __bases__, while deferring implementation internals.
Examples
Uses a small A-to-B inheritance hierarchy, a B instance, and interactive comparisons with type(), __name__, and __bases__.
What it assumes
Assumes familiarity with Python classes, instances, inheritance, and the type() function.
What you can do after
Evaluate an instance’s class and inspect its name or direct base classes.
How it connects
Connects __class__ with type(), __name__, __bases__, isinstance(), issubclass(), and class inheritance.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.