Skip to content

Module 11 · Object-Oriented Programming — topic 4 of 25

Attributes

Data stored on objects and classes: instance attributes, class attributes, reading and setting them with dot notation, getattr/setattr/hasattr, and attribute lookup order.

Beginner 10 min read·Lesson 161 of 306 in Python Programming

Learning objectives

  • Create and read instance and class attributes
  • Explain how Python looks up an attribute
  • Use getattr, setattr and hasattr for dynamic access

Definition

An attribute is a named value attached to an object, accessed with dot notation (obj.name). Instance attributes belong to a single object; class attributes are defined in the class body and shared by all instances.

Introduction

acc.balance, book.title, circle.radius — attributes are an object's data. They are created by assignment, usually inside __init__, and read with a dot.

Why it matters

Understanding where attributes live — on the instance or on the class — explains shared-state bugs and makes dynamic code (reading settings by name) possible.

Detailed explanation

Assigning self.name = value inside a method creates or updates an instance attribute stored in that object's __dict__.

A variable assigned directly in the class body is a class attribute shared by every instance.

Lookup order for obj.name: the instance's own attributes first, then the class, then its parent classes. If none has it, AttributeError is raised.

Assigning obj.name = value always writes to the instance, so it can shadow a class attribute of the same name for that one object.

getattr(obj, 'name', default) reads an attribute whose name is in a string; setattr(obj, 'name', value) sets it; hasattr(obj, 'name') tests for it; delattr removes it.

Syntax

Python
class Car:
wheels = 4 # class attribute
def __init__(self, model):
self.model = model # instance attribute
c = Car("Swift")
c.model, c.wheels # 'Swift', 4
getattr(c, "colour", "white") # 'white' (default)
  • self.x = ... creates instance attributes.
  • Class-body variables are shared.
  • Lookup: instance, class, parents.

Code examples

Instance and class attributes

Python
class Car:
wheels = 4
def __init__(self, model):
self.model = model
a, b = Car("Swift"), Car("Creta")
print(a.model, b.model, a.wheels, Car.wheels)
print(vars(a))
Output
Swift Creta 4 4
{'model': 'Swift'}

Dynamic access

Python
class Settings:
def __init__(self):
self.volume = 7
self.theme = "dark"
s = Settings()
for name in ["volume", "theme", "language"]:
print(name, getattr(s, name, "(not set)"))
setattr(s, "language", "en")
print(hasattr(s, "language"), s.language)
Output
volume 7
theme dark
language (not set)
True en

More examples

Shadowing a class attribute

Python
class Product:
tax_rate = 0.18
def __init__(self, name, price):
self.name = name
self.price = price
def total(self):
return round(self.price * (1 + self.tax_rate), 2)
book = Product("Book", 100)
phone = Product("Phone", 100)
book.tax_rate = 0.05 # instance attribute shadows the class one for book only
print(book.total(), phone.total())
Product.tax_rate = 0.12 # changes the shared default
print(book.total(), phone.total())
try:
print(phone.colour)
except AttributeError as e:
print("AttributeError:", e)
Output
105.0 118.0
105.0 112.0
AttributeError: 'Product' object has no attribute 'colour'

Step-by-step explanation

  • self.tax_rate finds the instance attribute if one exists, otherwise the class attribute.
  • Assigning book.tax_rate creates an attribute on book only; phone still uses the class value.
  • Changing Product.tax_rate affects every object that hasn't shadowed it.
  • Reading a missing attribute raises AttributeError naming the class and attribute.

Expected output

Running “Shadowing a class attribute” prints exactly:

TextOutput
105.0 118.0
105.0 112.0
AttributeError: 'Product' object has no attribute 'colour'

Practical applications

  • Configuration objects read by name with getattr.
  • Constants such as Account.MIN_BALANCE stored as class attributes.

Best practices

  • Create all instance attributes in __init__.
  • Use class attributes for constants and shared defaults only.
  • Use getattr with a default for optional attributes.

Common mistakes

Mutable class attributes

Avoid

class Team:
members = [] # shared by every team!
def add(self, m):
self.members.append(m)

Prefer

class Team:
def __init__(self):
self.members = []

A list defined in the class body is shared by all instances; create per-object lists in __init__.

Typos create new attributes

Avoid

acc.balnce = 100 # silently creates 'balnce'

Prefer

acc.balance = 100

Assignment never fails for misspelt names; use methods or __slots__ to catch such errors.

Important notes

  • __slots__ = ('x', 'y') restricts which attributes an instance can have and saves memory.

Key takeaways

  • Instance attributes belong to one object; class attributes are shared.
  • Lookup goes instance → class → parents.
  • getattr/setattr/hasattr access attributes by name.

Try it yourself

  1. 1
    Give a Student class a class attribute school and instance attributes name and roll.
  2. 2
    Print every attribute of an object using vars() and getattr().

Finished reading? Mark it complete to update your dashboard.

Suggested practice

16 questions cover the “Object-Oriented Programming” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module