Understanding Class Methods and Class Variables in Python
Class Methods
Class methods are defined on a class and can be invoked using the class name or an instance. They are declared with the @classmethod decorator and typically take cls as the first parameter, representing the clas itself. These methods can manipulate class variables but cannot access instance-specific data.
Syntax
class ExampleClass:
@classmethod
def example_class_method(cls, param1, param2):
# Implementation code
Key Characteristics
- Callable via class or instance: Class methods can be executed by referencing the class directly or through an instance.
- First parameter is the class: The initial argument, conventionally named
cls, refers to the class. - No instance variable access: Class methods operate on class-level data and cannot interact with instance attributes.
Example Usage
class Employee:
company = "TechCorp" # Class variable
def __init__(self, emp_name, emp_id):
self.name = emp_name # Instance variable
self.id = emp_id # Instance variable
@classmethod
def update_company(cls, new_company):
cls.company = new_company
# Invoke via class
Employee.update_company("InnovateInc")
print(Employee.company) # Output: InnovateInc
# Invoke via instance
emp = Employee("Bob", 101)
emp.update_company("FutureTech")
print(Employee.company) # Output: FutureTech
Class Variables
Class variables are defined within a class but outside any methods. They are shared across all instances and can be accessed or modified using the class name or an instance. Their value remains consistent unless explicitly altered.
Syntax
class ExampleClass:
shared_attribute = initial_value
Key Characteristics
- Shared across instances: All instance reference the same class variable.
- Accessible via class or instance: Both the class and its instances can read or write to class variables.
- Instance variable precedence: If an instance defines an attribute with the same name, it overrides the class variable for that instance.
Example Usage
class Employee:
company = "TechCorp" # Class variable
def __init__(self, emp_name, emp_id):
self.name = emp_name # Instance variable
self.id = emp_id # Instance variable
# Access via class
print(Employee.company) # Output: TechCorp
# Access via instance
emp = Employee("Alice", 102)
print(emp.company) # Output: TechCorp
# Modify class variable
Employee.company = "GlobalTech"
print(Employee.company) # Output: GlobalTech
print(emp.company) # Output: GlobalTech
# Override with instance variable
emp.company = "LocalBiz"
print(emp.company) # Output: LocalBiz
print(Employee.company) # Output: GlobalTech
Integrated Example
This example demonstrates the interaction between class methods and class variables.
class Rectangle:
default_color = "blue" # Class variable
def __init__(self, width, height):
self.width = width # Instance variable
self.height = height # Instance variable
@classmethod
def set_default_color(cls, color):
cls.default_color = color
def area(self):
return self.width * self.height
def describe(self):
return f"A {self.default_color} rectangle with area {self.area()}"
# Create instances
rect1 = Rectangle(4, 5)
rect2 = Rectangle(3, 7)
# Display descriptions
print(rect1.describe()) # Output: A blue rectangle with area 20
print(rect2.describe()) # Output: A blue rectangle with area 21
# Update class variable
Rectangle.set_default_color("green")
# Updated descriptions
print(rect1.describe()) # Output: A green rectangle with area 20
print(rect2.describe()) # Output: A green rectangle with area 21