Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
🧠 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: Canineprint(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
Feature | Class Variable | Instance Variable |
---|---|---|
Scope | Shared across all instances | Unique to each instance |
Declared In | Inside the class, outside methods | Usually in the __init__() |
Accessed With | ClassName.variable or self.variable | self.variable |
Use Case | Common data for all objects | Object-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
Feature | Class Method | Instance Method |
---|---|---|
First Arg | cls (refers to class) | self (refers to object) |
Access | Can access class variables | Can access instance variables |
Use Case | Factory methods, shared logic | Instance-specific behavior |
Decorator Required | @classmethod | No decorator |
⚒️ Practical Use Cases of Class Methods
-
Alternative Constructors
As shown earlier,@classmethod
can create objects using different input formats (e.g., from string, JSON, etc.). -
Tracking Objects
Use class variables to store objects or counts, and class methods to retrieve them. -
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
-
Mixing up
self
andcls
:self
is for instance methodscls
is for class methods
-
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 variableAlways use
ClassName.class_var
to modify it. -
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
Concept | Description | Keyword/Decorator |
---|---|---|
Class Variable | Shared by all instances | Defined at class level |
Instance Variable | Unique to each object | Defined in __init__() |
Class Method | Operates on class, not instance | @classmethod |
cls | Refers 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.