Skip to main content

Concept

ClassObject
A blueprint or template for creating objectsAn instance of a class
Defines attributes (data) and behaviours (methods) that objects will haveContains data and methods defined by the class, or has its own set of attribute values
Uses the class keywordCreated by calling the class like a function
Contains the __init__ method for initializationCreated using the class name followed by parentheses

Implementation

Let’s explore how to create classes and objects in Python.
1
Create a Class
2
To create a class in Python, use the class keyword followed by the class name. By convention, class names are written in CamelCase.
3
Car is your blueprint for creating car objects. It defines the attributes and methods that each car object will have.
4
class Car:
  # Class attributes (shared by all instances)
  wheels = 4

  def __init__(self, brand, model, year):
    self.brand = brand       # Instance attribute
    self.model = model       # Instance attribute
    self.year = year         # Instance attribute
    self.is_running = False  # Instance attribute

  def start(self):  # Instance method
    self.is_running = True
    print(f"{self.brand} {self.model} is now running.")

  def stop(self):  # Instance method
    self.is_running = False
    print(f"{self.brand} {self.model} has stopped.")
5
The __init__() method is the constructor that initializes the instance attributes when a new object is created. It takes self (the instance itself) and other parameters to set the initial state of the object. Attributes created in __init__() are called instance attributes and are unique to each object.
6
Create an Object
7
To create an object (instance), call the class like a function, passing the required arguments.
8
class Car:
  wheels = 4

  def __init__(self, brand, model, year):
    self.brand = brand
    self.model = model
    self.year = year
    self.is_running = False

  def start(self):
    self.is_running = True
    print(f"{self.brand} {self.model} is now running.")

  def stop(self):
    self.is_running = False
    print(f"{self.brand} {self.model} has stopped.")

# Creating objects (instances)
my_car = Car("BMW", "X5", 2020)
another_car = Car("Audi", "A4", 2021)

# Accessing attributes and methods
print(my_car.brand)   # BMW
my_car.start()        # BMW X5 is now running.
print(my_car.is_running)  # True

Class vs Instance Attributes

Attribute TypeScopeDefined In
Class attributeShared by all instances of the classDirectly inside the class body
Instance attributeUnique to each objectInside the __init__() method via self
Use class attributes for data that should be the same across all instances (like wheels = 4 for all cars). Use instance attributes for data that varies per object (like brand or model).

Build docs developers (and LLMs) love