Chapter 9: Object-Oriented Programming / Lesson 48

Class Methods

Class Methods and Static Methods

Python supports different types of methods: instance methods (regular methods), class methods, and static methods. Each serves a different purpose and is useful in different scenarios.

Understanding these method types helps you write more organized and efficient object-oriented code.

Instance Methods

Instance methods are the most common type. They take self as the first parameter and can access instance attributes:

instance_methods.py
class Circle: def __init__(self, radius): self.radius = radius # Instance method def area(self): return 3.14159 * self.radius ** 2 def circumference(self): return 2 * 3.14159 * self.radius circle = Circle(5) print(circle.area()) # 78.54 print(circle.circumference()) # 31.42

Class Methods

Class methods take cls as the first parameter and can access class attributes. They're defined with @classmethod decorator:

class_methods.py
class Student: total_students = 0 # Class attribute def __init__(self, name): self.name = name Student.total_students += 1 @classmethod def get_total(cls): return cls.total_students @classmethod def from_string(cls, student_str): # Alternative constructor name = student_str.split(",")[0] return cls(name) student1 = Student("Alice") student2 = Student("Bob") print(Student.get_total()) # 2 student3 = Student.from_string("Charlie, 20")

Static Methods

Static methods don't take self or cls. They're defined with @staticmethod and are utility functions related to the class:

static_methods.py
class MathUtils: @staticmethod def add(a, b): return a + b @staticmethod def multiply(a, b): return a * b # Can be called on class or instance result1 = MathUtils.add(5, 3) # 8 result2 = MathUtils.multiply(4, 2) # 8 print(result1, result2)

Best Practices

✅ Method Type Guidelines

• Use instance methods for operations on specific objects

• Use class methods for operations on the class itself or alternative constructors

• Use static methods for utility functions related to the class

• Don't use static methods if you need access to instance or class data

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...