After this lesson you can tell whether a value belongs to each individual object or to the whole class, and you will know the classic bug that comes from mixing them up.
Two places to keep data
So far every attribute was set through self inside __init__. Those are instance attributes: each object has its own copy. There is a second place for data, directly inside the class body. Those are class attributes, and there is only one copy, shared by every object.
A good rule: if the value can differ from object to object (a name, a price, a balance), it is an instance attribute. If it is the same for all of them (a tax rate, a shop name, a limit), it can be a class attribute.
class Item:
shop_name = "Corner Shop"
def __init__(self, name, price):
self.name = name
self.price = price
pen = Item("Pen", 2.5)
mug = Item("Mug", 6.0)
print(pen.name, pen.price)
print(mug.name, mug.price)
print(pen.shop_name, mug.shop_name)
print(Item.shop_name)Pen 2.5
Mug 6.0
Corner Shop Corner Shop
Corner ShopYou can reach a class attribute through the class itself (Item.shop_name) or through any object made from it.
How Python looks things up
When you read pen.shop_name, Python first checks whether pen itself has an attribute with that name. If not, it checks the class. That is why both objects can "see" the shop name even though neither stored it.
Changing the class attribute is visible to every object that has not set its own:
Item.shop_name = "Market Stall"
print(pen.shop_name, mug.shop_name)Market Stall Market StallAssigning through an object creates a new attribute
Here is a surprise for many beginners. If you assign to a name through an object, Python does not touch the class. It creates an instance attribute that hides the class one:
pen.shop_name = "Pen Kiosk"
print(pen.shop_name)
print(mug.shop_name)
print(Item.shop_name)Pen Kiosk
Market Stall
Market StallOnly pen changed. To change the shared value for everyone, assign through the class: Item.shop_name = ....
You can look at what an object stores itself with vars(), which shows the instance attributes only:
print(vars(pen))
print(vars(mug)){'name': 'Pen', 'price': 2.5, 'shop_name': 'Pen Kiosk'}
{'name': 'Mug', 'price': 6.0}The mug has no shop_name of its own, so it still reads the class value.
A useful job for class attributes: counting
Class attributes suit things like counters and constants. Here a class counts how many objects have been created:
class Member:
total_members = 0
max_loans = 3
def __init__(self, name):
self.name = name
Member.total_members += 1
Member("Asha")
Member("Ben")
Member("Chloe")
print(Member.total_members)
print(Member.max_loans)3
3The line Member.total_members += 1 names the class explicitly. That matters. Writing self.total_members += 1 would read the class value, add one, and store the result as a new instance attribute, leaving the class counter stuck at zero.
The shared list trap
The same sharing applies to lists and dictionaries, and here it usually hurts:
class Basket:
items = []
def add(self, item):
self.items.append(item)
first = Basket()
second = Basket()
first.add("bread")
second.add("milk")
print(first.items)
print(second.items)
print(first.items is second.items)['bread', 'milk']
['bread', 'milk']
TrueBoth baskets show both items, because there is only one list and append changes it in place. The fix is to create the list for each object inside __init__:
class Basket:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)
first = Basket()
second = Basket()
first.add("bread")
second.add("milk")
print(first.items)
print(second.items)['bread']
['milk']A video version of this topic is in the video course at /learn/python/.
Common mistakes
- Putting per-object data in the class body. If each object should have its own value, set it with
selfin__init__. - Using a list or dictionary as a class attribute. Everything shares it. Create mutable containers in
__init__. - Expecting
self.x = ...to update the class value. It creates a new instance attribute. UseClassName.x = ...to change the shared one. - Incrementing a counter through
self. WriteMember.total_members += 1. - Forgetting that old objects see class changes. Changing a class attribute affects every object that has not hidden it with its own value.
Exercise
Write a class Student with a class attribute school = "Greenfield High" and instance attributes name and marks. Add a class attribute count that goes up each time a student is created. Create three students and print the school, the count, and vars() of the first student.
Show one possible answer
class Student:
school = "Greenfield High"
count = 0
def __init__(self, name, marks):
self.name = name
self.marks = marks
Student.count += 1
a = Student("Asha", 82)
b = Student("Ben", 74)
c = Student("Chloe", 91)
print(Student.school)
print(Student.count)
print(vars(a))Greenfield High
3
{'name': 'Asha', 'marks': 82}Key points
- An instance attribute belongs to one object and is usually set in __init__ with self.name = value.
- A class attribute is written directly in the class body and is shared by every object of that class.
- Reading an attribute looks on the object first, then on the class.
- Assigning to self.count creates an instance attribute and does not change the class attribute of the same name.
- A mutable class attribute, such as a list, is shared by all objects, which usually causes bugs.