Part 09 / Topic 1 of 12
Why OOP
So far your data (lists, dicts) and your functions lived apart. You passed the data into the function every time. OOP (object-oriented programming) puts the data and the behaviour (the functions that work on that data) together in one unit.
- A class is a blueprint. It says what data a thing has and what it can do.
- An object is one real thing built from that blueprint. Another name for it is an instance.
- Data stored on an object is an attribute. A function that belongs to a class is a method.
Think of a house plan (the class) and the houses built from it (the objects). One plan, many houses, each with its own paint colour.
Real-world example: a student and their marks.
# Without a class: data and functions live apart
student = {"name": "Asha", "marks": [72, 95, 64]}
def average(s):
return sum(s["marks"]) / len(s["marks"])
print(average(student)) # 77.0
# With a class: the data and the behaviour travel together
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def average(self):
return sum(self.marks) / len(self.marks)
asha = Student("Asha", [72, 95, 64])
print(asha.average()) # 77.0
| Without classes | With classes |
|---|---|
| Data in a dict, functions somewhere else | Data and methods in one place |
| Easy to pass the wrong dict to a function | Each object knows its own data |
| Fine for small scripts | Better as the program grows |
๐ Going deeper: you have used objects since Part 2.
"hi".upper()calls theuppermethod of astrobject, andtype(5)shows<class 'int'>. In Python, everything is an object.
Done here? The practice set for Part 9 โ 8 exercises with solutions โ is on the part page.