liveBook · Manning

__name__ attribute

As explained in The Quick Python Book, Fourth Edition

The __name__ attribute of a class contains the class's defining name.

A class’s `__name__` attribute contains its defining name. If you have an instance rather than the class, first retrieve the class through the instance’s `__class__` attribute. section 17.3

Get a class name from an instance

```python class A: pass class B(A): pass b = B() b.__class__.__name__ # 'B' ``` The class object is also available as `B`; its `__bases__` attribute gives the base classes. Together, these attributes let you inspect an instance’s class and inheritance structure. section 17.3

Do not confuse a class’s `__name__` attribute with the module-level `__name__` variable. The latter is `'__main__'` when a file runs as a script and its module name when imported; it is commonly used to guard a call to `main()`. For ordinary type checks, `isinstance()` or `issubclass()` is usually more convenient than inspecting class attributes. section 11.1.3 section 17.3

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Demonstrates attribute access and related class inspection, but does not explore attribute implementation.
Examples
Shows an instance of subclass `B` yielding `'B'` through its class’s `__name__` attribute.
What it assumes
Assumes basic Python classes and instances; demonstrates how to retrieve the class object from an instance.
What you can do after
Evaluate/understand a class name retrieved from an instance, while distinguishing it from a module’s `__name__` variable.
How it connects
Connects class names to `__class__`, `__bases__`, inheritance, and the distinct module-level `__name__` variable.

Also explained in

Compare how 2 books explain __name__ attribute →

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.