Back to: Python Programming
An object is a “bundle” of related attributes (like variables, they describe what the object has) and methods (functions).
Example: On my desk I have a phone, a cup and a book. Each of these objects can have different attributes to represent it.
Attributes:
Phone – attributes include version_num = 15, is_on = TRUE, price = $800
Cup – attributes include liquid = “coffee”, temp = 85, is_empty = FALSE
Book – attributes include title = “Software Development”, pages = 333
Methods:
Objects have the capability to do things, they have methods which are functions that belong to an object. A method is a function that belongs within an object.
Phone – methods include def make_call():, def receive_call():, def turn_on():, def turn_off():
Cup – methods include def fill_cup():, def drink_cup():, def empty_cup():
Book – methods include def open_book():, def read_book():, def close_book():
Class:
To create many objects, we utilise a class. A class is a type of blueprint used to design the structure and layout of an object. We need to design what our objects have, their attributes, and what they can do, their methods. We will create a class of car and create some car objects. To construct a car object, we need a special type of method called a constructor, it works similarly to a function.
We need to use this method in order to create objects: def __init__(self): [to be discussed later]
Attributes:
class Car:
def __init__(self, model, year, colour, for_sale):
self.model = model
self.year = year
self.colour = colour
self.for_sale = for_sale
car1 = Car('Holden', '1971', 'red', False)
print(car1)
Outputs:
<__main__.Car object at 0x0000021712338B90>
Attempting to Print the object Car gives us the memory address of this car object.
If we want to access one of the attributes of the object, we will follow the name of the car object with a DOT. This dot is known as the “attribute access operator”. To print the model of car1, its year, colour and for sale status:
class Car:
def __init__(self, model, year, colour, for_sale):
self.model = model
self.year = year
self.colour = colour
self.for_sale = for_sale
car1 = Car('Holden HQ', '1971', 'red', False)
print(car1.model)
print(car1.year)
print(car1.colour)
print(car1.for_sale)
Outputs:
Holden HQ
1971
red
False
Now let’s create a second and third car. We’re going to reuse this class to create a car2 & car3:
car1 = Car('Holden HQ', '1971', 'red', False)
car2 = Car('Corvette', '2025', 'blue', True)
car3 = Car('Tesla', '2026', 'black', True)
Our code now looks like this:
class Car:
def __init__(self, model, year, colour, for_sale):
self.model = model
self.year = year
self.colour = colour
self.for_sale = for_sale
car1 = Car('Holden HQ', '1971', 'red', False)
car2 = Car('Corvette', '2025', 'blue', True)
car3 = Car('Tesla', '2026', 'black', True)
print(car2.model)
print(car2.year)
print(car2.colour)
print(car2.for_sale)
Classes are able to be stored in a completely different file for better organisation and ability for re-use. We can CUT the entire class and paste it in a new python file called car.py.
Into our main.py file we are going to import our car.py file (our car module).
We now have the two files:
car.py (storing the class)
class Car:
def __init__(self, model, year, colour, for_sale):
self.model = model
self.year = year
self.colour = colour
self.for_sale = for_sale
We also have the main.py that uses the class now imported from car.py
from car import Car
car1 = Car('Holden HQ', '1971', 'red', False)
car2 = Car('Corvette', '2025', 'blue', True)
car3 = Car('Tesla', '2026', 'black', True)
print(car2.model)
print(car2.year)
print(car2.colour)
print(car2.for_sale)
You can either keep your classes within the main python file, or import them if you would like to organise things a little more.
Methods
Methods are actions that our objects can perform. Within our class we will define a method of drive(self), stop(self) and describe(self).
car.py
class Car:
def __init__(self, model, year, colour, for_sale):
self.model = model
self.year = year
self.colour = colour
self.for_sale = for_sale
def drive(self):
print("You drive the car")
print(f"You drive the {self.model}")
print(f"You drive the {self.colour} {self.model}")
def stop(self):
print("You stop the car")
print(f"You stop the {self.model}")
print(f"You stop the {self.colour} {self.model}")
def describe(self):
print(f"{self.year} {self.colour} {self.model}")
main.py
from car import Car
car1 = Car('Holden HQ', '1971', 'red', False)
car2 = Car('Corvette', '2025', 'blue', True)
car3 = Car('Tesla', '2026', 'black', True)
# To print Attributes:
print(car2.model)
print(car2.year)
print(car2.colour)
print(car2.for_sale)
#To run Methods
car1.drive()
car2.stop()
car3.describe()
Outputs:
Corvette
2025
blue
True
You drive the car
You drive the Holden HQ
You drive the red Holden HQ
You stop the car
You stop the Corvette
You stop the blue Corvette
2026 black Tesla
Example
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
# Create a Circle object
circle = Circle(5)
# Calculate and print the area
print("Area:", circle.area())
# Calculate and print the perimeter
print("Perimeter:", circle.perimeter())
Explanation:
- Import the
mathmodule:This module provides mathematical functions, including the value of pi (math.pi). - Define the
Circleclass:- The
__init__method is the constructor, which takes the radius as an argument and initializes theradiusattribute of theCircleobject. - The
area()method calculates the area of the circle using the formulaπ * r^2and returns the result. - The
perimeter()method calculates the perimeter (circumference) of the circle using the formula2 * π * rand returns the result.
- The
- Create a
Circleobject:- An instance of the
Circleclass is created with a radius of 5.
- An instance of the
- Calculate and print area and perimeter:
- The
area()andperimeter()methods are called on thecircleobject, and their results are printed.
- The
This code will output the area and perimeter of a circle with a radius of 5.
Can you edit this example to ask the user to input a value for the radius?