Concept
| Class | Object |
|---|---|
| A blueprint or template for creating objects | An instance of a class |
| Defines attributes (data) and behaviours (methods) that objects will have | Contains data and methods defined by the class, or has its own set of attribute values |
Uses the class keyword | Created by calling the class like a function |
Contains the __init__ method for initialization | Created using the class name followed by parentheses |
Implementation
Let’s explore how to create classes and objects in Python.To create a class in Python, use the
class keyword followed by the class name. By convention, class names are written in CamelCase.Car is your blueprint for creating car objects. It defines the attributes and methods that each car object will have.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.")
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.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 Type | Scope | Defined In |
|---|---|---|
| Class attribute | Shared by all instances of the class | Directly inside the class body |
| Instance attribute | Unique to each object | Inside the __init__() method via self |