Site icon Spark By {Examples}

Python staticmethod vs classmethod

python staticmethod vs classmethod

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.

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:

See the following table that summarizes the differences between classmethod and staticmethod:

staticmethodclassmethod
First argumentNonecls (the class itself)
Use casesUtility 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 accessOnly other staticmethods and class-level attributesClass-level attributes and other classmethods, but not instance-level attributes
Method CallClassName.staticmethod_name()ClassName.classmethod_name() (Internally Different)
Decorator@staticmethod@classmethod
staticmethod vs classmethod

4. First argument – staticmethod vs classmethod

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

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!

Exit mobile version