Class variables are attributes defined directly inside a class body (outside any method) that are shared across the class itself and all of its instances, whereas defines a plain utility function namespaced inside a class that receives neither self (the instance) nor cls (the class) as an implicit first argument.
Basic Example
class Employee:
# 1. Class Variable: Shared across all instances of Employee
company_name = "Acme Corp"
employee_count = 0
def __init__(self, name: str, salary: float) -> None:
# Instance Variables: Unique per Employee object
self.name = name
self.salary = salary
# Mutate the class variable via the class name, NOT `self.employee_count += 1`
Employee.employee_count += 1
# 2. Static Method: Utility function grouped logically inside Employee (no `self` or `cls`)
@staticmethod
def is_valid_salary(amount: float) -> bool:
return amount >= 30_000
emp1 = Employee("Alice", 85_000)
emp2 = Employee("Bob", 95_000)
print(Employee.company_name, emp1.company_name) # Output: Acme Corp Acme Corp
print(Employee.employee_count) # Output: 2
print(Employee.is_valid_salary(45_000)) # Output: True (callable on class or instance)
print(emp1.is_valid_salary(20_000)) # Output: False
Key Details & Edge Cases
- Shadowing trap when assigning to a class variable via
self(self.x = ...):- Reading
self.company_namefalls back toEmployee.company_nameif"company_name"is not inself.__dict__. - However, assigning
emp1.company_name = "Beta LLC"(orself.employee_count += 1) does not update the class variable—it creates a new instance attribute onemp1that shadows the class attribute for that instance alone, leavingEmployee.company_nameandemp2.company_nameunchanged. Always update class variables viaClassName.attr = ...(orcls.attr = ...inside a).
- Reading
- Mutable class variable gotcha (
list/dictshared across instances):- Defining
tags = []at class level means every instance mutates the exact same list object (self.tags.append("a")mutatesEmployee.tagsin place without rebinding). Initialize per-instance mutable collections inside__init__(self.tags = []) unless shared state across all instances is explicitly intended.
- Defining
- Inheritance behavior for class variables vs.
:- Subclasses inherit class variables, and assigning
SubClass.company_name = "SubCo"creates an independent attribute onSubClasswithout alteringBaseClass.company_name. - Because
receives noclsreference, it cannot read or override subclass-specific class variables or construct subclass instances polymorphically—use(def from_string(cls, raw): ...) instead whenever a method needs access to class state or inheritance.
- Subclasses inherit class variables, and assigning
- When to use
vs.vs. a module-level function:- Choose
for pure helper/validation logic conceptually tied to the class API (e.g.,Date.is_leap_year(2028)) that requires zero access toselforcls(and can optionally be overridden by subclasses). - Choose
for alternative constructors (cls(...)) or methods that read/modify class variables (cls.count). - Choose a module-level function if the helper is general-purpose and has no conceptual tie to the class.
- Choose
Comparison of Python Method & Variable Types
| Construct | Decorator / Scope | Implicit 1st Arg | Can Access Instance State (self)? |
Can Access Class State (cls)? |
Best Used When |
|---|---|---|---|---|---|
| Class Variable | Defined in class body |
N/A | N/A | Shared across class & instances | Constants, counters, caches, or defaults shared by all instances. |
| Instance Variable | Assigned via self.x = ... |
N/A | Yes (unique per object) | No | Per-object state initialized in __init__. |
| Instance Method | None (def fn(self):) |
self (instance) |
Yes | Yes (type(self)) |
Standard behavior operating on a specific object’s data. |
| Class Method | |
cls (class) |
No | Yes | Alternative constructors (from_json) and subclass-aware class operations. |
| Static Method | |
None | No | Only by hardcoding ClassName |
Pure utility/validation helpers namespaced inside a class. |
You must log in or register to comment.
