Classes and Objects

A class is a blueprint. An object is a specific thing built from that blueprint. You can create as many objects as you like from a single class.

Defining a Class

class Car:
    pass  # empty for now — still a valid class
  • The class keyword starts the definition
  • Class names use PascalCase (first letter of each word capitalised)
  • The body is indented one level
  • pass means "do nothing yet" — useful for a class skeleton

Creating Objects (Instantiation)

car1 = Car()   # one object
car2 = Car()   # a different object
print(type(car1).__name__)   # → Car
print(isinstance(car1, Car)) # → True
print(car1 is car2)    # → False
Car
True
False

Calling Car() creates a brand-new, independent object each time.

Objects Have Identity

Two objects created from the same class still live separately in memory. They share a blueprint, but they are not the same thing.

class Dog:
    pass

d1 = Dog()
d2 = Dog()
print(type(d1).__name__)  # → Dog
print(isinstance(d1, Dog)) # → True
print(d1 is d2)            # → False
Dog
True
False

UML Class Diagram Notation

IB Computer Science uses UML (Unified Modelling Language) boxes to represent classes. Even when a class is still mostly a blueprint, the box shows the class name, attributes, and methods it will eventually have.

┌───────────────────────┐
│          Car          │  ← class name
├───────────────────────┤
│ + brand    : string   │  ← attributes (data)
│ + colour   : string   │
├───────────────────────┤
│ + accelerate()        │  ← methods (behaviour)
└───────────────────────┘
  • + means public (accessible from anywhere)
  • - means private (accessible only inside the class)
  • You will start adding attributes and methods in the next lessons

Your Task

  1. Write class Dog: and use pass in the body
  2. Create two Dog instances: d1 = Dog() and d2 = Dog()
  3. Print type(d1).__name__, isinstance(d1, Dog), and d1 is d2
Section 1/5Defining a Class

Defining a Class

Explore this concept

Classes and Objects

A class is a blueprint. An object is a specific thing built from that blueprint. You can create as many objects as you like from a single class.

Defining a Class

class Car:
    pass  # empty for now — still a valid class
  • The class keyword starts the definition
  • Class names use PascalCase (first letter of each word capitalised)
  • The body is indented one level
  • pass means "do nothing yet" — useful for a class skeleton

Output:

Click "Check" to run your code.