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
