Python 3D Academyবাংলা

Class attributes and instance attributes

🌍 In real life. Every student at your school shares the same school name, but each has their own roll number. It would be silly to write the school name separately for each student when it's the same for all. Python has both kinds:

  • an instance attribute, set with self. in a method, belongs to one object (the roll number)
  • a class attribute, written directly in the class body, belongs to the class, and every object shares it (the school name)

The idea in one sentence: an attribute set with self. belongs to one object, an attribute written in the class body belongs to the class and is shared by all its objects, and Python looks in the object first, then the class.

Its words:

  • instance attribute: self.roll = roll, one per object
  • class attribute: school = "Dhaka High" in the class body, one for everyone
  • lookup order: object first, then class; an object's own value hides the class's one

How does tripod.legs find its value? Python climbs a little tower: it looks in the object itself first, then in its class. The first place that has the name wins. So an object's own value hides the class's one. Watch the glowing probe climb:

class Dog:
    species = "Canis familiaris"
    legs = 4

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

rex = Dog("Rex")
tripod = Dog("Tripod")
tripod.legs = 3
print(rex.species, rex.legs)
print(tripod.species, tripod.legs)
tripod.legs = 3 gives tripod its own legs; rex still uses the class's 4.

A class attribute is the right place for a fact about the whole class, like how many robots a factory has made. Change it through the class name (Robot.made), so there is one shared count:

class Robot:
    made = 0

    def __init__(self, name):
        self.name = name
        Robot.made = Robot.made + 1

Robot("R2")
Robot("C3")
print(Robot.made)

Watch out: a list written in the class body is one list shared by every object, like one whiteboard for the whole class instead of a notebook each. Anything one student writes, everyone sees. If each object needs its own list, make it in __init__:

class Team:
    members = []          # one list, shared by every Team!

a = Team()
b = Team()
a.members.append("Ana")
print(b.members)

class BetterTeam:
    def __init__(self):
        self.members = [] # each team gets its own

c = BetterTeam()
d = BetterTeam()
c.members.append("Ana")
print(d.members)

Fixing the attributes: __slots__. Normally every object keeps its attributes in its own little dictionary, __dict__, so you can add any new attribute at any time, typos included: p.nmae = "Ana" quietly makes a second attribute. Writing __slots__ = ("x", "y") in the class body says "objects of this class have exactly these attributes". Python then leaves out the dictionary, which saves memory when you make millions of objects, and a misspelt attribute fails at once: AttributeError: 'Point' object has no attribute 'z' and no __dict__ for setting new attributes. Most classes don't need it; reach for it when you have very many small objects.

class Point:
    __slots__ = ("x", "y")

    def __init__(self, x, y):
        self.x = x
        self.y = y


p = Point(1, 2)
print(p.x, p.y, hasattr(p, "__dict__"))
try:
    p.z = 3
except AttributeError as e:
    print("refused:", e)

Why two kinds? A fact about the whole class (the school name, a shared counter) should be stored once: change it in one place, and every object sees the new value. A fact about one object (a roll number) must be stored on that object. Looking an attribute up costs one or two quick checks, object then class.

Mistakes and edge cases.

  • A shared list in the class body. Every object appends to the same list (above); make the list in __init__ instead.
  • Changing a class attribute through an object. robot.made = 5 creates a new attribute on that one robot and hides the shared one; write Robot.made = 5.
  • Expecting an instance value to change the class. Setting tripod.legs = 3 leaves Dog.legs as 4 for every other dog.

Quiz

  1. What does this print?

    class Car:
        wheels = 4
    
        def __init__(self, colour):
            self.colour = colour
    
    c = Car("red")
    print(c.wheels, c.colour)
  2. What does this print?

    class Car:
        wheels = 4
    
    a = Car()
    b = Car()
    b.wheels = 3
    print(a.wheels, b.wheels)
  3. What does this print?

    class Ticket:
        sold = 0
    
        def __init__(self):
            Ticket.sold = Ticket.sold + 1
    
    for i in range(3):
        Ticket()
    print(Ticket.sold)
  4. Where should a list go if every object needs its own?

    • In __init__, as self.items = []
    • In the class body, as items = []
    • It doesn't matter
  5. Which line causes every Basket to share one list?

    class Basket:
        fruits = []
    
        def add(self, fruit):
            self.fruits.append(fruit)
  6. What does this print?

    class Seat:
        __slots__ = ("row", "number")
    
        def __init__(self, row, number):
            self.row = row
            self.number = number
    
    
    s = Seat("B", 7)
    try:
        s.nubmer = 8
    except AttributeError:
        print("typo caught")
    print(s.row, s.number)

Coding tasks

  1. Write a class Robot with a class attribute made starting at 0. Each new Robot adds 1 to Robot.made.

  2. Write a class Dog with a class attribute species = "Canis familiaris" and an instance attribute name set in __init__.

  3. Write a class Team where each team has its own members list, and a method join(name) that adds a name to it.