Attribute

A piece of data stored on an object (or class), reached with a dot, like dog.name.

An attribute is a value attached to an object or a class. You usually create per-object attributes in __init__ by assigning to self, then read them with a dot: dog.name. Together, an object's attributes make up its state.

Attributes set on self belong to one object; attributes set in the class body are shared by every object of that class.

Example
class Book:
    pages = 0                  # class attribute (shared)

    def __init__(self, title):
        self.title = title     # instance attribute (per object)

b = Book("Python 101")
b.pages = 350                  # set an attribute
print(b.title, b.pages)
Output
Python 101 350

Where this shows up in real Python

Attributes hold an object’s state — a user’s name, an account’s balance — and they can differ from one instance to the next.

Commonly used Attribute tools

  • obj.attr — read or set an attribute directly
  • getattr(obj, 'x', default) — read by name, with a fallback
  • setattr(obj, 'x', value) — set by name
  • hasattr(obj, 'x') — check whether it exists

Related terms