Object-Oriented Python
Classes and Objects
A class is a blueprint. An object is one thing built from that blueprint, with its own data.
class Student:
school = "TechSnow" # shared by every student
def __init__(self, name, marks):
self.name = name # each student's own data
self.marks = marks
def grade(self):
return "A" if self.marks >= 80 else "B" if self.marks >= 60 else "C"
def __str__(self):
return f"{self.name} ({self.marks})"
ali = Student("Ali", 85)
sara = Student("Sara", 64)
print(ali, ali.grade())
print(sara, sara.grade(), sara.school)Output
Ali (85) A Sara (64) B TechSnow
__init__runs when a new object is created.selfis the object itself. Every method receives it first.__str__decides how the object looks when printed.