1
Classes and object
Python Classes/Objects 2
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and
methods.
A Class is like an object constructor, or a "blueprint" for creating
objects.
Class 3
How to create a class
How to create an object
Class 4
The __init__() Function
➢ The examples above are classes and objects in their simplest form, and are not really
useful in real life applications.
➢ To understand the meaning of classes we have to understand the built-in __init__()
function.
➢ All classes have a function called __init__(), which is always executed when the class is
being initiated.
➢ Use the __init__() function to assign values to object properties, or other operations
that are necessary to do when the object is being created:
Class 5
Class 6
The self Parameter:
The self parameter is a reference to the current instance of the class,
and is used to access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like,
but it has to be the first parameter of any function in the class:
Class 7
Modification of properties on objects
8
# Define a class called 'Car'
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"Car: {self.make} {self.model} ({self.year})")
# Create an object of the 'Car' class
my_car = Car("Tesla", "Model S", 2022)
# Access the attributes of the object and call its methods
print(f"Make: {my_car.make}")
print(f"Model: {my_car.model}")
print(f"Year: {my_car.year}")
my_car.display_info()
Modification of properties
class Car:
9
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"Car: {self.make} {self.model} ({self.year})")
# Create an object of the 'Car' class
my_car = Car("Tesla", "Model S", 2022)
# Display the initial information
my_car.display_info()
# Modify the properties of the car object
my_car.make = "BMW"
my_car.model = "X5"
my_car.year = 2023
# Display the modified information
my_car.display_info()
Class: 10
an example of a class called Circle that calculates the perimeter, area, and volume of a circle:
Exercise:
import math
class Circle:
def __init__(self, radius):
11
self.radius = radius
def calculate_perimeter(self):
return 2 * math.pi * self.radius
def calculate_area(self):
return math.pi * self.radius**2
def calculate_volume(self):
return (4/3) * math.pi * self.radius**3
# Create an object of the 'Circle' class
my_circle = Circle(5)
# Calculate and display the perimeter, area, and volume
print("Perimeter:", my_circle.calculate_perimeter())
print("Area:", my_circle.calculate_area())
print("Volume:", my_circle.calculate_volume())