Learning Outcomes- Define classes with attributes and methods
- Create and use objects
- Apply object-oriented concepts in programs
- Use Python standard libraries
Classes and Objects
A class is a user-defined blueprint for objects; the __init__ method initialises an object and self refers to the current instance. Objects are instances of a class, each holding its own attribute values.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
Methods
Methods are functions defined inside a class that operate on object data and are called on objects using dot notation.
class Student:
def __init__(self, name, marks):
self.name = name; self.marks = marks
def result(self):
return "Pass" if self.marks >= 40 else "Fail"
print(Student("Asha", 72).result())
Standard Libraries
Python ships with a rich standard library; modules such as math, random, datetime and statistics are imported to reuse well-tested functionality.
import math, random
print(math.sqrt(16), random.randint(1, 6))
Summary
This unit introduced classes, objects and methods, the basics of object-oriented programming in Python, and the use of standard library modules.
Exercises
- Create a class BankAccount with methods to deposit, withdraw and display the balance.
- Create a class to represent a rectangle and compute its area and perimeter.
- Use the math and random modules to build a simple number-guessing game.