Velamuvi AIAcademy

Lesson 4 of 15 · Classes and Objects

Instance and Class Attributes

Learn the difference between instance attributes and class attributes in Python, how Python looks them up, how to count objects and the shared-list trap to avoid.

  • 9 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • The difference between instance attributes and class attributes
  • How Python decides which one to use
  • How to keep a count of every object created
  • The shared-list mistake and how to avoid it

Two places data can live

So far, every attribute you have created was an instance attribute: Ada's name, Rex's age.

Sometimes, though, a piece of data is the same for every object of a class. Every dog is the species "Canis familiaris". Every account in a bank pays the same interest rate. Storing a copy of that value on every single object would be wasteful and hard to change.

Writing a class attribute

A class attribute is written directly inside the class, outside any method.

Try it yourselfPython
class Dog:
    species = "Canis familiaris"   # class attribute: shared by all dogs

    def __init__(self, name):
        self.name = name           # instance attribute: one per dog


rex = Dog("Rex")
bella = Dog("Bella")

print(rex.name, "|", rex.species)
print(bella.name, "|", bella.species)
print(Dog.species)

There is only one species value, stored on Dog. Both dogs can read it, and so can the class itself: Dog.species. Each dog's name, on the other hand, lives on that dog.

Instance attributeClass attribute
Writteninside a method, as self.x = ...directly in the class body
Belongs toone objectthe class, shared by all objects
Exampleself.namespecies = "..."
Use it fordata that differs between objectsdata that is the same for all of them

How Python finds an attribute

When you write rex.species, Python looks in two places, in order:

  1. On the object itself. Does rex have its own species? No.
  2. On the class. Does Dog have a species? Yes, so that value is used.

Think of it like asking a question at work. You first check your own notes. Only if the answer is not there do you look at the company handbook that everyone shares.

Changing a class attribute changes it for everyone

Because there is only one copy, changing it on the class affects every object, including ones that already exist.

Try it yourselfPython
class Account:
    interest_rate = 0.03

    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def yearly_interest(self):
        return self.balance * Account.interest_rate


a = Account("Ada", 1000)
b = Account("Alan", 2000)
print(a.yearly_interest(), b.yearly_interest())

Account.interest_rate = 0.05
print(a.yearly_interest(), b.yearly_interest())

One line changed the rate for every account. That is exactly what you want for shared settings.

The surprise: assigning through an object

Here is something that catches many people out. What happens if you assign to a class attribute through an object?

Try it yourselfPython
class Dog:
    species = "Canis familiaris"

    def __init__(self, name):
        self.name = name


rex = Dog("Rex")
bella = Dog("Bella")

rex.species = "Robot dog"

print(rex.species)
print(bella.species)
print(Dog.species)

Only Rex changed. This is called shadowing.

rex.species = ... did not change the shared value. It created a brand-new instance attribute on rex, which now hides the class attribute for Rex only. Remember the lookup order: Python checks the object first, finds Rex's own species, and stops there.

The rule: to change a class attribute for everyone, assign to the class: Dog.species = ....

A practical use: counting objects

A class attribute is a natural place to keep a running count of how many objects have been created.

Try it yourselfPython
class User:
    count = 0

    def __init__(self, name):
        self.name = name
        User.count += 1
        self.user_number = User.count


ada = User("Ada")
alan = User("Alan")
grace = User("Grace")

print("Users created:", User.count)
print(grace.name, "is user number", grace.user_number)

Notice User.count += 1, not self.count += 1. Writing self.count += 1 would read the shared value but then store the new value as an instance attribute on that one user, so the shared count would never go up.

Constants on the class

A class attribute is a tidy home for constants that belong to that class.

Try it yourselfPython
class Password:
    MIN_LENGTH = 8

    def __init__(self, text):
        self.text = text

    def is_strong(self):
        return len(self.text) >= Password.MIN_LENGTH


print(Password("hello").is_strong())
print(Password("velamuvi2026").is_strong())
print("Minimum length:", Password.MIN_LENGTH)

The shared-list trap

Never store a list or dictionary that should belong to each object as a class attribute. Watch what happens:

Try it yourselfPython
class Student:
    marks = []          # wrong: one list shared by every student

    def __init__(self, name):
        self.name = name


ada = Student("Ada")
alan = Student("Alan")
ada.marks.append(92)

print(alan.marks)

Alan has Ada's mark! There is only one marks list, stored on the class, and both students are using it. ada.marks.append(92) did not create anything new. It changed the one shared list.

The fix is to create the list inside __init__, so each object gets its own:

Try it yourselfPython
class Student:
    def __init__(self, name):
        self.name = name
        self.marks = []     # right: a new list for every student


ada = Student("Ada")
alan = Student("Alan")
ada.marks.append(92)

print(ada.marks)
print(alan.marks)

Common mistakes

Practice exercise

Use a class attribute to give every ticket its own number, in order.

Your solutionPython
# Write a class called Ticket.
# - A class attribute next_number that starts at 1
# - __init__(self, event) stores the event and gives the ticket
#   self.number = the current Ticket.next_number, then adds 1 to Ticket.next_number
# - A method label(self) that returns e.g. "Ticket 1: Concert"


first = Ticket("Concert")
second = Ticket("Concert")
third = Ticket("Workshop")
print(first.label())
print(third.label())
print("Next number:", Ticket.next_number)

# Output must be exactly:
# Ticket 1: Concert
# Ticket 3: Workshop
# Next number: 4
Knowledge check

A class has species = 'cat'. You run tom.species = 'tiger'. What does another cat, kitty.species, give?

Summary

  • Instance attributes (self.x = ...) belong to one object. Class attributes, written in the class body, are shared by all objects.
  • Python looks on the object first, then on the class.
  • Change shared values on the class: ClassName.x = .... Assigning through an object only hides the class value for that object.
  • Class attributes are good for shared settings, constants and counters.
  • Lists and dictionaries that belong to each object must be created in __init__.

You have finished the first module. Next, you will give your objects richer behaviour with methods.

Finished reading? Tick it off to track your progress.