Class Methods & Static Methods
Master different method types. Learn @classmethod, @staticmethod, and factory patterns.
Master different method types. Learn @classmethod, @staticmethod, and factory patterns. This hands-on tutorial focuses on practical implementation of class methods & static methods concepts.
Class Methods & Static Methods
Python has three types of methods: instance methods, class methods, and static methods. Each serves a different purpose.
Method Types Comparison
| Type | Decorator | First Parameter | Access To | Use Case |
|---|---|---|---|---|
| Instance | None | self | Instance & class | Regular methods |
| Class | @classmethod | cls | Class only | Factory methods, alternatives |
| Static | @staticmethod | None | Nothing | Utility functions |
Instance Methods (Review)
These are the regular methods you've been using. They receive self and can access instance attributes.
Class Methods: @classmethod π
Class methods receive the class itself as the first parameter (cls), not an instance.
Use cases:
- Factory methods (alternative constructors)
- Modify class state
- Access class variables
Static Methods: @staticmethod π§
Static methods don't receive self or cls. They're just regular functions that belong to the class namespace.
Use cases:
- Utility functions related to the class
- Functions that don't need instance or class data
Factory Pattern with Class Methods π
Class methods are perfect for creating alternative constructors.
When to Use Each Type π€
Coding Challenge: Employee Management System π
Create an Employee class with all three method types.
AI Mentor
Confused about "Python class methods static methods decorators"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 5What parameter does a class method receive?
Key Takeaways
β
Instance methods use self and access instance data.
β
Class methods use @classmethod and cls for class-level operations.
β
Static methods use @staticmethod for utility functions.
β
Factory pattern uses class methods for alternative constructors.
β
Choose based on what data you need to access.
What's Next?
In the next lesson, we'll do a Decorators Deep Dive - creating custom decorators and understanding how they work.
Keep coding! π