Learn
B3.1.4 | DEFINE CLASSES AND CREATE OBJECTS
01 | TURN A DESIGN INTO WORKING OBJECTS
A school owns tablets, laptops and robots. Each device needs its own identifier, display name and battery reading. A class describes this kind of object; construction creates particular devices with particular starting values.
This common SL/HL lesson constructs complete Python and Java classes and instantiates objects. We will connect constructor arguments to attributes, call instance methods and distinguish a second reference from a second object.
The focus is constructing and initializing instances. The next lesson develops encapsulation and information hiding; the first examples deliberately keep attribute access visible so the object model is easy to inspect.
02 | WRITE THE CONTRACT BEFORE THE CLASS
| Requirement | Implementation decision |
|---|---|
| Identify one device | Instance device_id as nonempty text |
| Show its label | Instance name as nonempty text |
| Track independent charge | Instance battery as integer percentage 0–100 |
| Start with a sensible value | Default battery 100 when omitted |
| Consume available charge | use_power(amount) returns success/rejection |
| Report current state | describe() returns a display string |
These are simplified percentage points, not a physical model of power consumption. The application supplies a unique ID; the class checks nonempty text but does not automatically check all other devices for duplicates.
A valid object starts with all required attributes and valid bounds. Avoid creating half-initialized objects that callers must repair through later assignments.
03 | THE SMALLEST MEANINGFUL DEFINITION
class Device:
def __init__(self, device_id, name):
self.device_id = device_id
self.name = name
robot = Device("D01", "Scout")
print(robot.device_id, robot.name)
The output is D01 Scout. class Device introduces the class definition. The indented __init__ method establishes instance state. Calling Device(...) constructs an instance and initializes it using those arguments.
Merely executing the class definition does not create a Scout device. The separate construction expression is what requests an instance.
04 | BREAK DOWN THE CONSTRUCTION STATEMENT
| Part of robot = Device("D01", "Scout") | Role |
|---|---|
| robot | Caller’s variable that will refer to the result |
| Device | Class being called to construct an instance |
| "D01", "Scout" | Arguments supplied for initialization |
| The whole Device(...) expression | Produces the initialized object when construction succeeds |
| Assignment = | Binds robot to that resulting object |
The variable name robot is not automatically stored inside the object. It is a reference used by the caller. You could instead call it first_device without changing the device_id stored as D01.
If initialization raises an exception, this assignment does not bind the name to a successfully constructed result. Existing bindings on the left are not replaced by a partial result.
05 | INITIALIZER PARAMETERS BECOME ATTRIBUTE VALUES
In def __init__(self, device_id, name), device_id and name are local parameter names. They receive the supplied values during that invocation. self.device_id and self.name are attributes stored on the receiving object.
The assignment self.name = name copies the reference to the supplied value into the object’s name attribute. The left and right sides are not the same variable merely because they share spelling.
Python supplies self automatically during normal construction. Do not pass a separate self argument in Device("D01", "Scout").
06 | WHAT A CONSTRUCTOR DOES
A constructor establishes a new object’s initial condition. It receives required values, applies defaults and can reject invalid inputs so callers do not receive a normally completed invalid instance.
Python __init__ is specifically the initializer called on a newly created instance during ordinary construction. It must not return the new object; reaching its end returns None. The class call, not a returned self from __init__, produces the constructed instance.
Java uses a constructor with the class name and no declared return type. Its new expression produces the reference to the new instance. These mechanisms serve related initialization goals with different syntax.
07 | SET DEFAULT STATE DELIBERATELY
class Device:
def __init__(self, device_id, name, battery=100):
self.device_id = device_id
self.name = name
self.battery = battery
robot = Device("D01", "Scout")
tablet = Device("D02", "Tablet", 60)
print(robot.battery, tablet.battery)
The output is 100 60. The omitted argument uses the default; the explicit 60 supplies a different valid initial value. Both instances still have separate battery attributes.
A default is part of the interface. It should match the requirement, rather than conceal a missing essential input. This short version illustrates defaults; the complete version next adds validation.
08 | CONSTRUCT THE COMPLETE DEVICE CLASS
class Device:
def __init__(self, device_id, name, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if not isinstance(name, str) or not name.strip():
raise ValueError("Name required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self.device_id = device_id.strip()
self.name = name.strip()
self.battery = battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self.battery:
return False
self.battery = self.battery - amount
return True
def describe(self):
return f"{self.device_id}: {self.name}, battery {self.battery}%"
The initializer validates before assigning the three attributes. Text is cleaned, and battery must be an actual integer in the inclusive range. This version deliberately rejects Boolean values and numeric text such as "60".
use_power changes only the receiver when the amount is valid and affordable; otherwise it returns False without mutation. describe returns text for the caller to display or reuse.
The same definition serves every Device instance. It does not hold one shared battery for the whole fleet.
09 | CREATE AND USE TWO INSTANCES
class Device:
def __init__(self, device_id, name, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if not isinstance(name, str) or not name.strip():
raise ValueError("Name required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self.device_id = device_id.strip()
self.name = name.strip()
self.battery = battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self.battery:
return False
self.battery = self.battery - amount
return True
def describe(self):
return f"{self.device_id}: {self.name}, battery {self.battery}%"
robot = Device("D01", "Scout")
tablet = Device("D02", "Tablet", 60)
print(robot.use_power(20))
print(robot.describe())
print(tablet.describe())
Outputs: True; D01: Scout, battery 80%; D02: Tablet, battery 60%. The method uses robot as self, so the tablet is unaffected.
The method definitions are shared behaviour, while the attribute values are instance state. Use this distinction to predict a call before running it.
10 | THE DOT SELECTS A MEMBER OF A RECEIVER
| Expression | Meaning |
|---|---|
| robot.battery | Read the battery attribute of robot’s object |
| robot.describe() | Call that object’s description method |
| robot.use_power(20) | Request a state change on that object |
| Device("D03", "Spare", 50) | Construct another instance |
| Device | Refer to the class object in Python without constructing a device |
Parentheses matter. robot.describe refers to a bound method; robot.describe() invokes it. Likewise spare = Device stores the class in a variable, whereas spare = Device(...) normally constructs an instance.
An instance attribute and an instance method both use member access, but they play different roles. A battery number is not called as battery().
11 | ONE OBJECT CAN HAVE TWO REFERENCES
class Device:
def __init__(self, device_id, name, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if not isinstance(name, str) or not name.strip():
raise ValueError("Name required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self.device_id = device_id.strip()
self.name = name.strip()
self.battery = battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self.battery:
return False
self.battery = self.battery - amount
return True
def describe(self):
return f"{self.device_id}: {self.name}, battery {self.battery}%"
robot = Device("D01", "Scout")
alias = robot
alias.use_power(15)
print(robot.battery)
print(alias is robot)
Outputs: 85 and True. alias = robot does not call the class and does not create a second device. Both names refer to the same object, so a mutation through either name is visible through the other.
An alias is another reference to the same object. Use is in Python to test identity; equality using == is a different concept and may be customized by a class.
This is not the same as a class variable shared by all instances. Aliasing involves multiple references to one instance.
12 | EQUAL STARTING VALUES DO NOT MERGE OBJECTS
class Device:
def __init__(self, device_id, name, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if not isinstance(name, str) or not name.strip():
raise ValueError("Name required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self.device_id = device_id.strip()
self.name = name.strip()
self.battery = battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self.battery:
return False
self.battery = self.battery - amount
return True
def describe(self):
return f"{self.device_id}: {self.name}, battery {self.battery}%"
a = Device("D01", "Scout", 80)
b = Device("D01", "Scout", 80)
a.use_power(10)
print(a.battery, b.battery)
print(a is b)
Outputs: 70 80 and False. Two construction calls produced two separate instances even though their starting field values matched.
The duplicated D01 intentionally exposes the difference between object identity and application identity. This class does not enforce globally unique device IDs. A real managing collection or storage system must reject duplicate IDs if that is required.
Do not assume constructors invent uniqueness merely because a field is named ID.
13 | INTERACTIVE: FOLLOW CONSTRUCTION AND ALIASING
Step through a fixed Python program. The model labels objects A and B for explanation; these labels are not literal memory addresses or stored device IDs. Watch references separately from object attributes.
The sequence creates a robot and tablet, gives the robot an alias, changes it through that alias, and then rebinds the original variable to the tablet. Predict whether an operation creates an object, changes state or only changes a reference.
14 | REBINDING A NAME DOES NOT COPY OR ERASE STATE
After alias = robot, both names refer to the first object. If robot = tablet then executes, robot now refers to the tablet object, but alias still refers to the original robot object.
The assignment changes a binding, not the old object’s attributes. The original object remains reachable through alias and can still receive method calls.
Do not infer that an object is deleted when one variable is rebound. Lifetime and garbage collection depend on remaining references and language/runtime rules; the visible reference trace is enough for this example.
15 | OBJECTS IN COLLECTIONS
class Device:
def __init__(self, device_id, name, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if not isinstance(name, str) or not name.strip():
raise ValueError("Name required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self.device_id = device_id.strip()
self.name = name.strip()
self.battery = battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self.battery:
return False
self.battery = self.battery - amount
return True
def describe(self):
return f"{self.device_id}: {self.name}, battery {self.battery}%"
devices = [Device("D01", "Scout", 80),
Device("D02", "Tablet", 60)]
for device in devices:
print(device.describe())
devices[0].use_power(10)
print(devices[0].battery)
The first outputs describe the two initial devices, then 70 is printed. The list stores references to objects. Indexing the list selects a reference, and the method call acts on that object.
Construct inside the loop when you require a new object per iteration. Reusing one already created object and appending it repeatedly produces repeated references to that same object, not independent devices.
16 | CREATE A SEPARATE MUTABLE ATTRIBUTE PER OBJECT
class ReadingLog:
def __init__(self, device_id):
self.device_id = device_id
self.readings = []
a = ReadingLog("D01")
b = ReadingLog("D02")
a.readings.append(80)
print(a.readings, b.readings)
The output is [80] []. Each initializer invocation creates a new list. Putting readings = [] in the class body instead could share one list across unshadowed instance lookups.
A mutable default parameter such as readings=[] can also be reused across calls. Use a safe design such as readings=None and create a new list inside when no list is supplied. If a supplied collection should be copied, make that policy explicit.
17 | VALIDATION FAILURE DOES NOT PRODUCE A NORMAL RESULT
class Device:
def __init__(self, device_id, name, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if not isinstance(name, str) or not name.strip():
raise ValueError("Name required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self.device_id = device_id.strip()
self.name = name.strip()
self.battery = battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self.battery:
return False
self.battery = self.battery - amount
return True
def describe(self):
return f"{self.device_id}: {self.name}, battery {self.battery}%"
try:
invalid = Device("D03", "Spare", 150)
except ValueError as error:
print(error)
The message is Battery must be an integer from 0 to 100. Construction did not complete normally, so a new name invalid is not bound by this failed assignment.
For a previously bound variable, the old binding remains if evaluating its replacement raises before the assignment. Do not describe that as successful creation with a warning.
In this example, validating before attribute assignments simplifies the initialization contract. Avoid publishing a partly initialized self to other objects during construction.
18 | THE INITIALIZER MUST BE NAMED CORRECTLY
| Error | Consequence |
|---|---|
| def init(...) instead of __init__ | Ordinary method; not the expected Python initializer |
| __init__ returns self | TypeError: initializer should return None |
| device_id = device_id instead of self.device_id = device_id | Only local parameter work; missing instance attribute |
| Call use_power without a receiver | No instance selected for the operation |
| Pass too few required constructor arguments | Argument error before normal completion |
| Create a shared mutable list unintentionally | Independent objects can appear to change together |
Use the exact double underscores in __init__ and keep body indentation consistent. A class can exist even when its intended initializer was misspelled, so test an actual construction and attribute access.
19 | JAVA: DEFINE THE FIELDS AND CONSTRUCTORS
public class DeviceExample {
static class Device {
private final String deviceId;
private final String name;
private int battery;
Device(String deviceId, String name) {
this(deviceId, name, 100);
}
Device(String deviceId, String name, int battery) {
if (deviceId == null || deviceId.trim().isEmpty()
|| name == null || name.trim().isEmpty()
|| battery < 0 || battery > 100) {
throw new IllegalArgumentException("Invalid initial device state");
}
this.deviceId = deviceId.trim();
this.name = name.trim();
this.battery = battery;
}
boolean usePower(int amount) {
if (amount < 0 || amount > battery) {
return false;
}
battery = battery - amount;
return true;
}
String describe() {
return deviceId + ": " + name + ", battery " + battery + "%";
}
}
public static void main(String[] args) {
Device robot = new Device("D01", "Scout");
Device tablet = new Device("D02", "Tablet", 60);
robot.usePower(20);
System.out.println(robot.describe());
System.out.println(tablet.describe());
}
}
Outputs: D01: Scout, battery 80%; D02: Tablet, battery 60%. Fields are declared in the class; constructors initialize them. this.deviceId identifies the instance field while deviceId alone names the constructor parameter.
The two-argument constructor delegates to the three-argument constructor with 100, so validation is centralized. This is constructor overloading, not Python-style default parameters. The nested class keeps the complete example in one file.
20 | JAVA NEW, REFERENCES AND IDENTITY
In Device robot = new Device(...), Device declares the reference type, robot names the reference variable and new requests an instance through the chosen constructor. A declaration such as Device robot; alone creates no Device object.
Assigning another = robot copies the reference value, not the entire Device. Both references can reach the same mutable object. Reassigning one reference later does not change the other reference.
Java == on object references tests identity. equals may express a class-defined equality rule; it does not automatically mean every class compares all its fields. Python is tests identity, while == can invoke value-equality behaviour.
21 | MAP A CLASS DESIGN TO CODE
| Design element | Python implementation | Java implementation |
|---|---|---|
| Class Device | class Device: | class Device { ... } |
| Instance attribute battery | self.battery initialized per instance | Non-static field battery |
| Creation with ID/name | Device(id, name) | new Device(id, name) |
| Starting battery default 100 | Default parameter battery=100 | Overloaded constructor delegating with 100 |
| Receiver-based operation | self and bound instance method | this and instance method |
| Text description result | return an f-string | Return a String |
A UML operation signature supplies a contract, but naming and type notation may map differently to the chosen language. Keep the expected behaviour and initialization rules consistent.
The next objective focuses on controlling access. Public Python attributes in these introductory examples can still be changed directly by callers, so the methods alone do not enforce every future state update.
22 | COMPLETE SCENARIO: CONSTRUCT A SMALL FLEET
class Device:
def __init__(self, device_id, name, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if not isinstance(name, str) or not name.strip():
raise ValueError("Name required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self.device_id = device_id.strip()
self.name = name.strip()
self.battery = battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self.battery:
return False
self.battery = self.battery - amount
return True
def describe(self):
return f"{self.device_id}: {self.name}, battery {self.battery}%"
initial_data = [("D01", "Scout", 80), ("D02", "Tablet", 60)]
devices = []
for device_id, name, battery in initial_data:
device = Device(device_id, name, battery)
devices.append(device)
for device in devices:
if device.use_power(10):
print(device.describe())
else:
print("Insufficient battery:", device.device_id)
The descriptions show Scout at 70% and Tablet at 50%. Each loop construction creates an independent object; the list retains references so they can be used later.
The example assumes the supplied IDs are unique. A complete importer would need a defined policy for duplicates and invalid rows, and would not imply that partially importing valid rows is always acceptable.
23 | TEST INITIAL STATE AND OBJECT INDEPENDENCE
class Device:
def __init__(self, device_id, name, battery=100):
if not isinstance(device_id, str) or not device_id.strip():
raise ValueError("Device ID required")
if not isinstance(name, str) or not name.strip():
raise ValueError("Name required")
if type(battery) is not int or not 0 <= battery <= 100:
raise ValueError("Battery must be an integer from 0 to 100")
self.device_id = device_id.strip()
self.name = name.strip()
self.battery = battery
def use_power(self, amount):
if type(amount) is not int or amount < 0 or amount > self.battery:
return False
self.battery = self.battery - amount
return True
def describe(self):
return f"{self.device_id}: {self.name}, battery {self.battery}%"
a = Device("D01", "Scout")
b = Device("D02", "Tablet", 60)
assert a.battery == 100
assert b.battery == 60
assert a is not b
assert a.use_power(20) is True
assert a.battery == 80
assert b.battery == 60
alias = a
assert alias is a
assert alias.use_power(5) is True
assert a.battery == 75
assert a.use_power(100) is False
assert a.battery == 75
With assertions enabled, a normal run produces no output. The checks cover default and supplied initialization, separate instances, alias visibility and rejection without mutation.
Also test battery 0 and 100, an empty ID, a blank name, non-integer values and invalid point consumption. Trace the expected state after every successful or rejected operation.
24 | CONSTRUCT IT: A QUIZ ATTEMPT
A QuizAttempt is created for a nonempty student ID. Each object starts with score 0 and submitted False. add_marks accepts a non-negative integer before submission and returns success; submit changes its own submitted state. Create two attempts and show their independence.
Reveal one possible implementation
class QuizAttempt:
def __init__(self, student_id):
if not isinstance(student_id, str) or not student_id.strip():
raise ValueError("Student ID required")
self.student_id = student_id.strip()
self.score = 0
self.submitted = False
def add_marks(self, marks):
if self.submitted or type(marks) is not int or marks < 0:
return False
self.score = self.score + marks
return True
def submit(self):
if self.submitted:
return False
self.submitted = True
return True
a = QuizAttempt("S01")
b = QuizAttempt("S02")
a.add_marks(4)
a.submit()
print(a.score, a.submitted)
print(b.score, b.submitted)
Outputs: 4 True, then 0 False. This simplified contract has no maximum score. Add a maximum only when the requirements define one, and decide which layer verifies student existence.
25 | COMMON CONSTRUCTION CONFUSIONS
| Confusion | Correction |
|---|---|
| Writing a class creates all required objects | Instantiate each required object explicitly |
| The caller’s variable name is the object’s ID | Store a separate ID attribute when required |
| __init__ should return self | Python class construction returns the object; __init__ initializes it and returns None |
| Assignment creates a copy of an instance | Ordinary reference assignment creates an alias |
| Identical fields imply one object | Separate constructions can create distinct instances with equal values |
| Rebinding robot changes the old object | Rebinding changes that name’s reference |
| A constructor guarantees globally unique IDs | Uniqueness needs a managing rule |
| A method-only validation policy prevents direct edits | Access control and information hiding need their own design |
26 | A COMPLETE CONSTRUCT RESPONSE
Define the class, initialize every required instance attribute, state defaults and reject invalid initial values. Add the specified methods with correct receiver use, returned results and state transitions.
Show actual construction calls with appropriate arguments and a small demonstration or test. If the question asks for several independent objects, call construction for each rather than assigning multiple names to one instance.
Trace references separately from object state. The next lesson applies encapsulation and information hiding to control how callers access and change those attributes.