Part 09 / Topic 3 of 12
Methods, class attributes, @classmethod, @staticmethod
- An instance method is a normal
definside the class. Its first parameter isself, so it can read and change that object's data. - A class attribute is written directly inside the class (not on
self). It is shared by all objects. Use it for things that are the same for everyone, or for counting objects. - A class method (
@classmethod) gets the class itself asclsinstead of an object. The common use is an alternative constructor: another way to make an object, such as from a string. - A static method (
@staticmethod) gets neitherselfnorcls. It is a plain helper function that lives in the class because it belongs there.
A @ line above a def is a decorator: it changes how the function below it works. You only need to use them here; Part 10 shows how they work inside.
Think of a school: every student has their own roll number (instance attribute), but they all share the same school name (class attribute).
Real-world example: students joining a school.
class Student:
school = "Sunrise Public School" # class attribute: shared
count = 0 # class attribute: counts students
def __init__(self, name: str, roll_no: int):
self.name = name # instance attributes: one per object
self.roll_no = roll_no
Student.count += 1
def badge(self) -> str: # instance method
return f"{self.roll_no}: {self.name} ({self.school})"
@classmethod
def from_string(cls, text: str): # alternative constructor
name, roll = text.split(",")
return cls(name.strip(), int(roll))
@staticmethod
def is_valid_roll(roll_no: int) -> bool: # helper, no self or cls
return 1 <= roll_no <= 999
asha = Student("Asha", 12)
ravi = Student.from_string("Ravi, 21")
print(asha.badge()) # 12: Asha (Sunrise Public School)
print(ravi.badge()) # 21: Ravi (Sunrise Public School)
print(Student.count) # 2
print(Student.is_valid_roll(1200)) # False
| Kind | First parameter | Can use | Typical use |
|---|---|---|---|
| Instance method | self |
This object's data | Most methods |
@classmethod |
cls |
The class | Alternative constructors like from_string |
@staticmethod |
none | Only its arguments | Small helper or check |
Careful: writing a class attribute through an object makes a new instance attribute that hides the shared one.
class Student:
school = "Sunrise Public School"
a = Student()
b = Student()
a.school = "Moonlight School" # creates a new attribute on a only
print(a.school) # Moonlight School
print(b.school) # Sunrise Public School
Student.school = "Sunrise Global School" # change the shared value
print(b.school) # Sunrise Global School
Full program: examples/01_student_records.py.
๐ Going deeper:
from_stringusescls(...), notStudent(...). That way a child class (section 5) that callsfrom_stringgets an object of the child class.
Done here? The practice set for Part 9 โ 8 exercises with solutions โ is on the part page.