-
Can only access class-level stuff, not with the object
-
The first argument is always
cls(likeself, but for class) -
Used when you want to access or modify class-level stuff
Bank Analogy:
Suppose your bank gives a standard interest rate to all savings accounts
class BankAccount:
interest_rate = 0.05 # class-level property
@classmethod
def update_interest_rate(cls, new_rate):
cls.interest_rate = new_rate
print(f"Updated interest rate to {cls.interest_rate}")
-
All accounts will get the new rate
-
No need to create an object to update it
How do I know it’s class level or object level?
If you write it inside the constructor (__init__), then it becomes an object-level property.
Each object will have its own copy of that property.
Example:
class BankAccount:
def __init__(self, holder):
self.holder = holder # object-level
self.interest_rate = 0.05 # object-level
-
Now
self.interest_rateis tied to each object -
You can change it for one object, it won’t affect others
But this one is class-level: because it is not written inside the constructor (__init__)
class BankAccount:
interest_rate = 0.05 # class-level
-
This is shared among all objects
-
If you change it with
cls.interest_rate, it updates for everyone
Simple Difference:
Defined where? | Belongs to? | Can access using? |
|---|---|---|
Inside class (outside methods) | Class-level | Class name or |
Inside constructor ( | Object-level | Object name or |