Skip to content

Python Classes, Object Identity, and Shared State

Step 21 of 41

Python Classes and Objects: Identity, Equality, and References

Introduction

Python classes group state with the methods that use it. To trace their behavior, distinguish an object from the names that refer to it: second = first creates another reference, while a fresh instance can hold independent state. Identity and value equality answer different questions.

This lesson opens PCAP-31-03 Object-Oriented Programming (34% of the score, 12 of 40 items). It covers objective 4.1 and the identity comparisons in 4.5. You will model warehouse records, follow shared references, and choose between is and ==.

Learning objectives

After this lesson you can:

  1. Define the vocabulary of object-oriented programming: class, object (instance), property (attribute), method, encapsulation.
  2. Write a class with an initializer and create several independent instances.
  3. Trace references: explain what an assignment between two names copies and what it does not copy.
  4. Use is, is not, == and id() correctly, and predict their results.
  5. Explain what the default == does for instances of your own classes and how it differs from the behaviour of built-in types.
  6. Model a real-world situation (a warehouse, a ticket queue) with classes and relate objects through references.

The vocabulary of objects

A class is a description: it states which data an object of that kind carries and which operations it supports. An object (also called an instance) is one concrete thing built from that description. The class Bin describes warehouse bins in general; Bin("A-01", 100) is one particular bin.

Term Meaning Python example
Class Blueprint that defines the shared behaviour class Bin:
Object / instance A concrete value created from a class b = Bin("A-01", 100)
Property (attribute) A named piece of data attached to an object or class b.location
Method A function defined inside a class, called on an object b.free_space()
Encapsulation Bundling data with the methods that use it, and controlling access to the data a _stock attribute changed only through add()
Initializer Sets up an instance after allocation def __init__(self, ...)

In Python everything you handle is already an object: integers, strings, lists, functions, even classes themselves. A class statement simply lets you create new kinds of objects. This is why the vocabulary of this lesson applies equally to your own types and to built-in ones.

Why classes at all?

Imagine a warehouse script that stores each bin as a dictionary and passes it around. Nothing stops one function from spelling the key "stock" and another from spelling it "qty". A class collects the data and the operations that are valid for it in one place, so the rules are written once. The exam does not ask you to argue about design, but it does ask you to read classes quickly, so you should find the structure natural.

The syllabus uses “property” broadly for an attribute. Python’s built-in property is a specific descriptor mechanism for managed attributes; it is not a synonym for every stored value.

Defining a class and creating instances

Python
class Bin:
    def __init__(self, location, capacity):
        self.location = location
        self.capacity = capacity
        self.items = 0

    def add(self, count):
        self.items += count

    def free_space(self):
        return self.capacity - self.items


a = Bin("A-01", 100)
b = Bin("B-07", 40)
a.add(30)
print(a.items, b.items)          # 30 0
print(a.free_space(), b.free_space())   # 70 40

Read this slowly, because every line carries a rule.

  • class Bin: creates a class object and binds it to the name Bin.
  • Bin("A-01", 100) creates a new empty instance, then calls __init__ with that instance as the first argument (self) followed by the arguments you wrote. See Python methods and object initialization for how allocation and initialization differ. Here, self is the instance being initialized.
  • self.location = location creates an attribute on that instance. Attributes are created by assignment; there is no declaration step.
  • a.add(30) changes a only. b.items is still 0, because the two instances each have their own attribute storage.

The result of Bin(...) is the object. The name a is just a label pointing to it. Keep this distinction in mind throughout the lesson: names refer to objects; they are not the objects.

Attributes belong to objects

These plain instances have dictionaries and support adding attributes outside the class. Other types may restrict that operation, for example through __slots__. For this Bin:

Python
a.owner = "Night shift"
print(a.owner)      # Night shift
print(b.owner)      # AttributeError: 'Bin' object has no attribute 'owner'

The second print raises AttributeError, because owner was added to a only. This flexibility is legal Python and appears in exam code, but good designs create all attributes in __init__ so that every instance has the same shape.

References: the core of object tracing

Assignment never copies an object. It makes a name point to the same object that another name already points to.

Python
bin_a = Bin("A-01", 100)
bin_b = bin_a            # no new object is created

bin_b.add(25)
print(bin_a.items)       # 25
print(bin_a is bin_b)    # True

This snippet creates one new Bin instance. bin_a and bin_b are two names for it, so a change made through one name is visible through the other. Track that shared object before evaluating later mutations.

Compare with creating two separate objects that happen to have the same data:

Python
x = Bin("C-02", 50)
y = Bin("C-02", 50)
print(x is y)            # False
x.add(10)
print(y.items)           # 0

With this ordinary class and its inherited allocator, the two calls create distinct instances. This is not a universal rule for every callable class: custom __new__ or metaclass behavior can reuse an object.

Objects stored in other objects

An object can hold a reference to another object as an attribute. This is how real models are built:

Python
class Product:
    def __init__(self, sku, name):
        self.sku = sku
        self.name = name


class Slot:
    def __init__(self, label, product):
        self.label = label
        self.product = product      # a reference, not a copy


chair = Product("CH-100", "Office chair")
slot1 = Slot("A-01", chair)
slot2 = Slot("B-04", chair)

chair.name = "Ergonomic chair"
print(slot1.product.name)     # Ergonomic chair
print(slot2.product.name)     # Ergonomic chair
print(slot1.product is slot2.product)   # True

Both slots refer to the same Product. Renaming the product through the name chair changes what both slots report. This is exactly the situation of the practice scenario for this lesson: two warehouse bins referencing the same inventory object.

Identity versus equality

Python offers two different questions about two values.

Operator Question How it is decided
a is b Are a and b the same object? Compares identity (id(a) == id(b))
a is not b Are they different objects? Negation of is
a == b Are the values equal under their comparison protocol? Uses rich comparison methods, with a possible reflected comparison or identity fallback

id(obj) returns an integer that is unique for the object during its lifetime. For two simultaneously live objects, equal ids mean they are the same object. An id can be reused after the earlier object’s lifetime, so do not treat it as a permanent record identifier.

Python
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

print(list1 == list2)    # True, same contents
print(list1 is list2)    # False, two different lists
print(list1 is list3)    # True, same object
print(id(list1) == id(list3))   # True

The default == for your own classes

For built-in containers == compares contents. For the plain classes below, with no custom equality inherited or defined, == falls back to identity. A subclass can inherit value equality, so check its bases as well.

Python
p = Product("CH-100", "Office chair")
q = Product("CH-100", "Office chair")
print(p == q)     # False
print(p == p)     # True

Two products with identical attributes are not equal, because Python has not been told how to compare them. The PCAP syllabus does not require you to write __eq__, but you must predict this result. If you do define it, the class itself decides what "equal" means:

Python
class Money:
    def __init__(self, cents):
        self.cents = cents

    def __eq__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return self.cents == other.cents


print(Money(500) == Money(500))   # True
print(Money(500) is Money(500))   # False

Even here is still reports False: == is customizable, is is not. Returning NotImplemented for an unsupported operand lets Python try the other operand’s comparison. If neither supports equality, == falls back to identity.

Small integers, strings and is

Exam items sometimes show is on literals. CPython may reuse objects for small integers and some strings, so the result can look surprising:

Python
a = 256
b = 256
print(a is b)       # True in CPython (small integers are cached)

c = 10 ** 6
d = 10 ** 6
print(c == d)       # True

Do not rely on is for numbers or strings: it is an implementation detail, not a language guarantee. Use == for values and keep is for identity questions, most often x is None. In the exam, if a question compares values with is, the safe reading is that the answer depends on object identity and that equal values do not guarantee it.

Shared references and mutable state

The behaviour that surprises beginners is mutation through a shared reference. The same event is harmless with immutable values and meaningful with mutable ones.

Python
class Shelf:
    def __init__(self, contents):
        self.contents = contents      # stores the reference it received


stock = ["bolts", "nuts"]
s1 = Shelf(stock)
s2 = Shelf(stock)

s1.contents.append("washers")
print(s2.contents)      # ['bolts', 'nuts', 'washers']
print(stock)            # ['bolts', 'nuts', 'washers']

The list was created once, and all three names point to it. append mutates the list in place, so the change is visible everywhere. Compare with rebinding:

Python
s1.contents = ["screws"]     # s1 now points to a brand new list
print(s2.contents)           # ['bolts', 'nuts', 'washers']

Assigning a new object to s1.contents does not touch the old list. This difference between mutating an object and rebinding a name is at the heart of many tracing questions.

For these string items, list(stock), stock[:], or stock.copy() provides an independent outer list. These are shallow copies: nested mutable objects would still be shared. Review Python instance and class attributes to distinguish such sharing from a class-level list.

Encapsulation at this level

Encapsulation means keeping an object's data behind a controlled interface. Python does not enforce it; it relies on conventions and on name mangling (covered in the next lesson). The simplest form is the convention of a leading underscore:

Python
class Counter:
    def __init__(self):
        self._value = 0          # by convention: internal

    def increment(self):
        self._value += 1

    def value(self):
        return self._value


c = Counter()
c.increment()
c.increment()
print(c.value())     # 2

Nothing prevents c._value = 99; the underscore says "do not do this". What the class gained is a single place where the rule "a counter only goes up by one" is written.

Worked example: two bins, one inventory record

Statement. A warehouse tracks pallets of a product in InventoryRecord objects. Two bins, bin_north and bin_south, were set up with what the author believed were separate records. After the code below runs, what are the values printed, and which lines show that the records are actually shared?

Python
class InventoryRecord:
    def __init__(self, sku, quantity):
        self.sku = sku
        self.quantity = quantity


class StorageBin:
    def __init__(self, label, record):
        self.label = label
        self.record = record

    def remove(self, count):
        self.record.quantity -= count


shared = InventoryRecord("VALVE-9", 100)
bin_north = StorageBin("N-1", shared)
bin_south = StorageBin("S-1", shared)
bin_east = StorageBin("E-1", InventoryRecord("VALVE-9", 100))

bin_north.remove(30)
bin_south.remove(20)
bin_east.remove(10)

print(bin_north.record.quantity)
print(bin_south.record.quantity)
print(bin_east.record.quantity)
print(bin_north.record is bin_south.record)
print(bin_north.record is bin_east.record)
print(bin_north.record == bin_east.record)

Step 1: count the objects. shared is one InventoryRecord. The expression InventoryRecord("VALVE-9", 100) in the bin_east line creates a second one. So two records and three bins exist.

Step 2: follow the references. bin_north.record and bin_south.record both point to the first record (quantity 100). bin_east.record points to the second record.

Step 3: execute the removals. bin_north.remove(30) subtracts 30 from the first record: 70. bin_south.remove(20) subtracts 20 from the same record: 50. bin_east.remove(10) subtracts 10 from the second record: 90.

Step 4: evaluate the prints.

Text
50
50
90
True
False
False

The first two lines are both 50 because they read the same record. The third is 90. The is tests confirm sharing for north/south and separation for north/east. The final == is False because the class does not define __eq__, so equality falls back to identity. The records share a SKU but now have quantities 50 and 90; Python is not comparing either attribute in this test.

Why other readings are wrong. Answering 70 / 80 / 90 assumes each bin has its own copy: it treats the constructor argument as a value copy, but Python passes the reference. Answering True on the last line assumes that == compares attribute values, which only happens if __eq__ is written. Answering 50 / 50 / 100 ignores that bin_east.remove(10) really runs.

Common pitfalls and exam tips

Pitfall What happens How to avoid it
Believing b = a copies the object Mutation through either reference affects the shared object Say "second name, same object" aloud
Using is to compare values Works for small ints by accident, fails elsewhere Use == for values, is for identity and None
Assuming == compares instance attributes automatically Plain classes retain identity equality Check the class and its bases for custom equality
Assuming distinct ordinary instances must share state Separate allocations are confused with aliases Count allocations and inspect referenced mutable values
Mutating versus rebinding obj.items.append(x) changes everyone, obj.items = [...] changes one holder Ask "did the object change, or only the name?"
Adding attributes outside __init__ Only one instance has the attribute Create all attributes in the initializer

Exam tip. In any tracing question, draw the objects as boxes and the names as arrows before reading the print statements. For the ordinary classes shown here, mark each construction as a new box; assignments between names add arrows. This technique converts most OOP items into simple lookups.

Exam tip. When == appears, check the class and inherited equality behavior. For the plain classes in this lesson, identity determines the result.

Exam tip. The statement "Python has no real private attributes" is true, but the syllabus names two mechanisms (underscore convention and name mangling). Distinguish the naming convention from the compiler’s name rewrite; neither is a security boundary.

End-of-lesson case study

Situation. A support team models tickets and queues. A developer wrote the following code and reports that "closing one ticket closes both". Explain what happens and propose the minimal fix.

Python
class Ticket:
    def __init__(self, number):
        self.number = number
        self.open = True

    def close(self):
        self.open = False


class Queue:
    def __init__(self, tickets):
        self.tickets = tickets


urgent = Ticket(101)
normal = urgent
first = Queue([urgent])
second = Queue([normal])

first.tickets[0].close()
print(second.tickets[0].open)
print(second.tickets[0] is first.tickets[0])

Solution, commented. normal = urgent does not create a second ticket: both names refer to ticket 101. The two queues each hold a list, but both lists contain the same ticket. first.tickets[0].close() sets open to False on that single object, so second.tickets[0].open prints False, and the is test prints True.

The behaviour is not a bug of Python; it is the code expressing the same ticket twice. If two separate tickets were intended, the fix is to create them separately: normal = Ticket(102), which produces a second object with its own open attribute. If the two queues should truly share the ticket (a ticket visible in two views), the code is already right and the developer's expectation is the problem.

Key terms

  • Class: a definition that describes the data and behaviour of a kind of object.
  • Object / instance: a concrete value created from a class.
  • Property / attribute: a named value attached to an object or a class.
  • Method: a function defined in a class and called on an object.
  • Encapsulation: keeping data together with the methods that manage it, and limiting direct access by convention.
  • Reference: the link from a name (or an attribute) to an object.
  • Identity: the fact of being one specific object, tested by is and shown by id().
  • Equality: having equal values according to __eq__; falls back to identity for plain classes.

Summary checklist

  • I can say what a class is, what an instance is, and how the two relate.
  • I know that attributes are created by assignment and belong to one object.
  • I can trace a program in which several names share one object.
  • I distinguish mutating an object from rebinding a name.
  • I know that == on a plain class behaves like is.
  • I use is for None and identity, == for values.
  • I can model a small real-world situation with objects that reference one another.

Official sources