Built In Class Attributes

Every Python class automatically comes with a set of built-in attributes that provide useful information about the class itself, without you needing to define them manually.

Common Built-In Class Attributes

  • __dict__ - a dictionary containing the class's namespace, including its attributes and methods
  • __doc__ - the class's docstring, if one has been written
  • __name__ - the name of the class as a string
  • __module__ - the name of the module in which the class was defined
  • __bases__ - a tuple containing the class's parent (base) classes
class Student:
    """Represents a student enrolled in a course."""
    def __init__(self, name):
        self.name = name

print(Student.__name__)    # Student
print(Student.__doc__)     # Represents a student enrolled in a course.
print(Student.__module__)  # __main__
These built-in attributes are especially useful for debugging, introspection, and writing generic code that needs to inspect classes without knowing their exact structure in advance.

Coming Up Next

Next, you'll learn how Python controls access to class attributes and methods through public, protected, and private conventions.

A Few More Attributes Worth Knowing

AttributeAvailable onWhat it gives you
__qualname__ClassThe dotted name including any enclosing class, such as Outer.Inner
__mro__ClassMethod resolution order: the exact sequence Python searches for attributes
__annotations__ClassType hints declared on the class body
__class__InstanceThe class that created the object
__dict__InstanceThe object's own attribute values, separate from the class namespace

Class Namespace Versus Instance Namespace

A frequent point of confusion is that a class and each of its objects have separate dictionaries. Class-level data such as shared counters lives in the class; values set in __init__ live on each instance.

class Model:
    """Simple model wrapper."""
    framework = "sklearn"          # class attribute

    def __init__(self, name, depth):
        self.name = name           # instance attributes
        self.depth = depth

m = Model("tree", 4)

print(m.__dict__)                  # {'name': 'tree', 'depth': 4}
print("framework" in m.__dict__)   # False - it lives on the class
print(type(Model.__dict__))        # <class 'mappingproxy'>
print(m.__class__.__name__)        # Model
print(Model.__bases__)             # (<class 'object'>,)

When you read m.framework, Python checks the instance dictionary first, then the class, then parent classes in __mro__ order. Assigning m.framework = "torch" adds a new entry to the instance only; the class value stays the same for other objects.

Worked Example: Inspecting Inheritance

class Base:
    pass

class Regressor(Base):
    pass

class LinearRegressor(Regressor):
    pass

print(LinearRegressor.__bases__)
# (<class '__main__.Regressor'>,)

print([c.__name__ for c in LinearRegressor.__mro__])
# ['LinearRegressor', 'Regressor', 'Base', 'object']

__bases__ shows only the direct parents, while __mro__ walks the whole chain. The built-in functions issubclass() and isinstance() rely on this same chain, so they are the cleaner choice for everyday type checks. With multiple inheritance, __mro__ is the reliable way to know which parent's method will actually be used.

Practical Uses and Pitfalls

In data work, these attributes help you write small generic helpers. For example, a logging function can record an experiment by reading obj.__class__.__name__ and vars(obj), so the same function works for any model wrapper you write. The built-in vars() returns the same thing as __dict__, and dir() lists every attribute reachable from an object, including inherited ones.

def describe(obj):
    return {"type": obj.__class__.__name__, **vars(obj)}

print(describe(m))   # {'type': 'Model', 'name': 'tree', 'depth': 4}

Keep these points in mind:

  • Class.__dict__ is read-only; trying Model.__dict__["x"] = 1 raises TypeError. Use setattr(Model, "x", 1) instead.
  • __doc__ is None when no docstring is written, so check before calling string methods on it.
  • Classes that define __slots__ usually have no per-instance __dict__, so vars(obj) fails for them.
  • __module__ is "__main__" when code runs as a script but becomes the real module name once imported, which matters for saved models and pickling.
  • Double-underscore names are for reading and introspection; avoid inventing your own names in that style, because Python reserves them.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course