Python · OOP: classes and objects
Defining classes, __init__ and self, instance vs class attributes, methods, and properties.
A class is a blueprint, and an object (instance) is one thing built from it.
__init__runs when an object is created and sets up the instance attributes.selfis the instance itself. Python passes it automatically, soobj.method(x)becomesClass.method(obj, x).- Class attributes are defined in the class body and shared by every instance. Instance attributes are set on
selfand belong to one object. @propertylets a method be read like an attribute. That’s useful for computed values or for validating input.
class Student:
university = "PDEU" # class attribute (shared)
def __init__(self, name, marks):
self.name = name # instance attributes
self._marks = marks
@property
def marks(self):
return self._marks
@marks.setter
def marks(self, value):
if not 0 <= value <= 100:
raise ValueError("marks must be 0..100")
self._marks = value
def passed(self, cutoff=40):
return self._marks >= cutoff
a = Student("Sahaj", 88)
b = Student("Ravi", 35)
print(a.name, a.marks, a.passed(), b.passed())
print(a.university, b.university, Student.university)
a.marks = 91
print(a.marks)
try:
a.marks = 150
except ValueError as e:
print("ValueError:", e)
print(Student.passed(b, cutoff=30)) # what a.method() really does
Output:
Sahaj 88 True False
PDEU PDEU PDEU
91
ValueError: marks must be 0..100
TrueSources
- Classes — Python Software Foundation
- Built-in functions: property — Python Software Foundation
- Class and instance variables — Python Software Foundation