What is the Difference between staticmethod vs classmethod in Python? In this article, we will explore the differences between staticmethod
and classmethod
in Python, when to use each method, and provide examples of how to implement them in your Python code. The staticmethod
and classmethod
decorators are used to define methods that are related to a class but are not specific to any instance of the class.
Table of contents
1. What is staticmethod?
A staticmethod in Python is a special type of method that is defined inside a class and is related to the class but does not have access to any instance or class data.
This means that a staticmethod
is not bound to any specific instance of the class, and can be called on the class itself without the need for an instance.
A staticmethod
is used to define a utility function that is related to the class, but does not require access to any instance or class data.
To define a static method in Python, you need to use the @staticmethod
decorator. Here’s an example of how to define a staticmethod
in Python:
# Static method
class MyClass:
@staticmethod
def my_static_method(arg1, arg2):
return arg1 + arg2
In the above code, we’ve defined the staticmethod
, we can call it directly on the class, like this:
# Call static method from the class
result = MyClass.my_static_method(2, 3)
print(result)
# Output: 5
2. What is classmethod?
In Python, classmethod
is a type of method that is defined inside a class and is related to the class as a whole rather than a specific instance of the class.
It is similar to a staticmethod
, but it can access and modify the class itself. A classmethod
is defined using the @classmethod
decorator, which tells Python to treat the method as a class method.
An important feature of a classmethod
is that it takes the class as its first argument, which is typically called cls
. This means that it can be used to create methods that work with the class data in a way that regular instance methods cannot.
Following is a simple example of creating a classmethod
:
# Define class method
class MyClass:
counter = 0
def __init__(self, name):
self.name = name
MyClass.counter += 1
@classmethod
def display_count(cls):
print("The count is:", cls.counter)
obj1 = MyClass("Ali")
obj2 = MyClass("NNK")
MyClass.display_count()
# Output: The count is: 2
I hope it is clear what are staticmethod vs classmethod in Python and now let’s look at the differences between them.
3. Difference Between saticmethod vs classmethod
The main difference between a staticmethod
vs a classmethod
in Python is in how they handle the arguments that are passed to them.
A staticmethod
takes no special first argument. It behaves like a regular function, but is defined inside a class for organizational purposes. While, a classmethod
takes the class as its first argument, which allows it to modify class-level attributes.
Differences between staticmethod
and classmethod
in Python:
- Decorator:
classmethod
is a decorator method, which means it can be used to modify the behavior of other methods in the class.staticmethod
is not a decorator. - Access to class data:
classmethod
has access to the class data through itscls
parameter, whilestaticmethod
does not have any knowledge of the class data. This means thatclassmethod
can modify class-level attributes or perform operations on the class itself, whilestaticmethod
cannot. - Access to instance data:
classmethod
can access instance data if it is passed as an argument, whilestaticmethod
cannot. This means thatclassmethod
can modify or access the data of a specific instance, whilestaticmethod
cannot. - Method call: both
staticmethod
andclassmethod
can be called on the class itself without the need for an instance, but the way they are called is slightly different.staticmethod
is called like a regular function, whileclassmethod
is called using the class name and the method name, likeClassName.method_name()
See the following table that summarizes the differences between classmethod
and staticmethod
:
staticmethod | classmethod | |
---|---|---|
First argument | None | cls (the class itself) |
Use cases | Utility functions that are related to the class but don’t require access to instance or class data. | Factory methods that create instances of the class or modify class-level attributes. |
Can access | Only other staticmethods and class-level attributes | Class-level attributes and other classmethods, but not instance-level attributes |
Method Call | ClassName.staticmethod_name() | ClassName.classmethod_name() (Internally Different) |
Decorator | @staticmethod | @classmethod |
4. First argument – staticmethod vs classmethod
staticmethod
has no special first argument, and it behaves like a regular function.classmethod
has a first argument ofcls
, which refers to the class itself. This argument is used to allow the method to modify or access class-level attributes.
See the following example:
class MyClass:
class_variable = "Hello"
def __init__(self, instance_variable):
self.instance_variable = instance_variable
@staticmethod
def static_method():
print("doesn't use the instance or class")
@classmethod
def class_method(cls):
print("uses the class variable:", cls.class_variable)
obj = MyClass("world")
obj.static_method()
# output: doesn't use the instance or class
obj.class_method()
# output: uses the class variable: Hello
5. Access to Attribute – staticmethod vs classmethod
staticmethod
cannot access any instance or class data. It is essentially just a regular function that happens to be defined within a class namespace. Therefore,staticmethod
can only operate on arguments that are passed to it.classmethod
can access the class data, but not the instance data directly. Since the first argument of aclassmethod
is the class itself, it can access any class-level attributes or methods. It cannot access instance-level attributes or methods directly.
See the following example
class MyClass:
class_attr = 10
def __init__(self, inst_attr):
self.inst_attr = inst_attr
@staticmethod
def static_method(val):
# Can only operate on arguments passed to it
return val * 2
@classmethod
def class_method(cls, val):
# Can access class-level attributes
return val * cls.class_attr
# Example usage:
obj = MyClass(5)
print(obj.static_method(3))
# Output: 6
print(obj.class_method(3))
# Output: 30
6. Usage – classmethod and staticmethod
Ths staticmethod
is often used to define utility functions that are related to the class, but do not require access to any instance or class data. For example, imagine a class representing a mathematical vector.
A staticmethod
could be used to define a dot product calculation function that takes two vectors as arguments and returns their dot product.
The classmethod
is often used for operations that require access to class data or for creating new instances of the class. For example, imagine a class representing a database connection.
A classmethod
could be used to create a new connection to the database, or to set a default connection that all instances of the class will use.
Another common use case for classmethod
is as an alternative constructor. You might have a class that can be initialized with multiple different sets of parameters, and using a classmethod
as a factory method can help to make the code more readable and maintainable.
See the example of using classmethod
as a constructor:
class MyClass:
counter = 0
def __init__(self, name):
self.name = name
MyClass.counter += 1
@classmethod
def from_string(cls, name_string):
name = name_string.strip().title()
return cls(name)
@classmethod
def display_count(cls):
print("The count is:", cls.counter)
obj1 = MyClass("Ali")
obj2 = MyClass("NNK")
MyClass.display_count()
# Output: The count is: 2
obj3 = MyClass.from_string("Hamza")
MyClass.display_count()
# Output: The count is: 3
7. Summary and Conclusion
We explained the difference between staticmethod
vs classmethod
and the importance of them in object-oriented programming in Python. I hope now you understand the differences between staticmethod
and classmethod
. Let me know if you have any questions.
Happy coding!
Related Articles
- Stack in Python Explained with Examples
- Static Methods in Python Explained
- Python Get Class Name of an Instance
- Python Stack LifoQueue Methods