Python Class Methods
🐍 Python Class Methods — Complete Guide
In Python, class methods are methods that operate on the class itself, not on instances (objects).
They are defined using the @classmethod decorator.
🔹 1️⃣ Key Points About Class Methods
-
Decorated with
@classmethod. -
First parameter is
cls, which refers to the class, not the instance. -
Can access class variables but cannot access instance variables directly.
-
Can be called on the class or on an instance.
🔹 2️⃣ Basic Syntax
Call the method:
Or via object:
🔹 3️⃣ Example: Incrementing a Class Variable
🔹 4️⃣ Factory Method Using Class Method
Class methods can also be used as factory methods to create objects with alternative constructors.
🔹 5️⃣ Difference Between Instance Method and Class Method
| Feature | Instance Method | Class Method |
|---|---|---|
| Decorator | None | @classmethod |
| First Parameter | self (object) |
cls (class) |
| Access | Instance variables | Class variables |
| Call | On object only | On object or class |
🔹 6️⃣ Class Method vs Static Method (Quick Comparison)
| Feature | Class Method | Static Method |
|---|---|---|
| Decorator | @classmethod |
@staticmethod |
| First Param | cls |
None |
| Access | Class variables | Cannot access class or instance vars |
| Use | Factory methods, class-level logic | Utility functions |
🔹 7️⃣ Real-World Example: Bank Account
✅ Summary
-
Instance Method → works on object (
self) -
Class Method → works on class (
cls) -
Static Method → utility method, independent of object/class
