Python Class Methods

🐍 Python Class Methods

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



 3️⃣ Example: Incrementing a Class Variable


 

Employee.total_employees() # Total Employees: 2


 4️⃣ Factory Method Using Class Method

Class methods can also be use as factory methods to create objects with alternative constructors.


 


 5️⃣ Difference Between Instance Method and Class Method

FeatureInstance MethodClass Method
DecoratorNone@classmethod
First Parameterself (object)cls (class)
AccessInstance variablesClass variables
CallOn object onlyOn object or class

 6️⃣ Class Method vs Static Method (Quick Comparison)

FeatureClass MethodStatic Method
Decorator@classmethod@staticmethod
First ParamclsNone
AccessClass variablesCannot access class or instance vars
UseFactory methods, class-level logicUtility functions

 7️⃣ Real-World Example: Bank Account


 

Bank.bank_info() # Bank: ABC Bank, Total Accounts: 2


✅ Summary

  • Instance Method → works on object (self)

  • Class Method → works on class (cls)

  • Static Method → utility method, independent of object/class

You may also like...