Python

Python Basics

Data Structures in Python

Control Flow and Loops

Functions and Scope

Object-Oriented Programming (OOP)

Python Programs


🧠 Class Variables and Methods (@classmethod) in Python

Python is a flexible and intuitive programming language, especially known for its object-oriented programming (OOP) capabilities. Two fundamental OOP concepts in Python that often confuse beginners are class variables and class methods (decorated using @classmethod).

While similar in appearance to instance variables and methods, class variables and methods behave very differently. If you’re new to Python or transitioning into OOP, this guide will help you confidently understand and apply them in your code.


📌 What Are Class Variables?

A class variable is a variable that is shared across all instances of a class. It is defined inside the class but outside any instance methods. All objects of the class have access to the same copy of this variable.

✅ Example:

class Dog:
species = "Canine" # class variable
def __init__(self, name):
self.name = name # instance variable
dog1 = Dog("Buddy")
dog2 = Dog("Charlie")
print(dog1.species) # Output: Canine
print(dog2.species) # Output: Canine

No matter how many Dog objects you create, the species remains the same unless explicitly changed at the class level.


🧾 Class Variable vs Instance Variable

FeatureClass VariableInstance Variable
ScopeShared across all instancesUnique to each instance
Declared InInside the class, outside methodsUsually in the __init__()
Accessed WithClassName.variable or self.variableself.variable
Use CaseCommon data for all objectsObject-specific data

⚙️ Why Use Class Variables?

Class variables are useful when you want to:

  • Share configuration or default settings across all instances
  • Count number of instances (e.g., object counters)
  • Maintain shared resources like a list of all objects

🛠️ Real-World Example: Tracking Instance Count

class Employee:
employee_count = 0 # class variable
def __init__(self, name):
self.name = name
Employee.employee_count += 1 # increment class variable
emp1 = Employee("Alice")
emp2 = Employee("Bob")
print("Total Employees:", Employee.employee_count) # Output: 2

This demonstrates how class variables can be used to track something across all instances.


🔹 What Is a Class Method?

A class method is a method that operates on the class itself, rather than the object instance. It is declared with the @classmethod decorator and takes cls (not self) as the first parameter.

This allows class methods to modify class variables or return objects based on class-level logic.


✅ Syntax:

class MyClass:
@classmethod
def my_class_method(cls, args):
# cls refers to the class, not the instance

✅ Example:

class Circle:
pi = 3.14159 # class variable
def __init__(self, radius):
self.radius = radius
@classmethod
def from_diameter(cls, diameter):
return cls(diameter / 2)
c1 = Circle.from_diameter(10)
print(c1.radius) # Output: 5.0

This example shows how a class method can be used as an alternative constructor, using class data.


🔎 Class Method vs Instance Method

FeatureClass MethodInstance Method
First Argcls (refers to class)self (refers to object)
AccessCan access class variablesCan access instance variables
Use CaseFactory methods, shared logicInstance-specific behavior
Decorator Required@classmethodNo decorator

⚒️ Practical Use Cases of Class Methods

  1. Alternative Constructors
    As shown earlier, @classmethod can create objects using different input formats (e.g., from string, JSON, etc.).

  2. Tracking Objects
    Use class variables to store objects or counts, and class methods to retrieve them.

  3. Configuration Setup
    If your class requires shared settings (like default values or environment setup), class methods help initialize or modify those.


🧩 Combining Class Variables and Class Methods

Let’s look at a real-world example where both class variables and class methods are used together.


🔸 Real-World Example: Managing Users

class User:
users = [] # class variable
def __init__(self, username):
self.username = username
User.users.append(self)
@classmethod
def all_users(cls):
return [user.username for user in cls.users]

Now you can create and retrieve users easily:

u1 = User("alice")
u2 = User("bob")
print(User.all_users()) # Output: ['alice', 'bob']

This structure is helpful for user management systems, game scores, or active sessions.


🛡️ Common Mistakes to Avoid

  1. Mixing up self and cls:

    • self is for instance methods
    • cls is for class methods
  2. Changing class variables through instances:

    • This creates a new instance variable instead of modifying the shared one
    obj1 = MyClass()
    obj1.class_var = "New" # Wrong - this creates a new instance variable

    Always use ClassName.class_var to modify it.

  3. Not using the @classmethod decorator:

    • If you forget the decorator, your method won’t work as a class method.

✅ Best Practices

  • Use class variables for data shared among all instances.
  • Use class methods when the logic relates to the class itself.
  • Avoid mutating class variables unintentionally through instances.
  • Use meaningful names like from_json, from_file, etc., for class method constructors.

🧾 Summary Table

ConceptDescriptionKeyword/Decorator
Class VariableShared by all instancesDefined at class level
Instance VariableUnique to each objectDefined in __init__()
Class MethodOperates on class, not instance@classmethod
clsRefers to the class inside class methods

🎓 Final Thoughts

Mastering class variables and @classmethod in Python unlocks the power of scalable, maintainable, and efficient object-oriented code. These features are especially useful in real-world applications like:

  • Data models
  • Factory patterns
  • Object tracking
  • User/session management systems

When used wisely, they can greatly improve the design of your Python applications and make your code more Pythonic and professional.