Python - What are Static and Class Methods?

Have you ever seen some Python code and wondered what @staticmethod and @classmethod do ?
In short, they are both methods that modify the default binding that the instance methods provide. Lets dive in some more...

Static Methods

A static method is a method that knows nothing about the class or instance it was called on. The class instance therefore is NOT passed in as an implicit first argument to the static method.

def a_static_method(x):
return x

The main advantages to using static methods are that Python does not have to instantiate a bound-method for object. Additionally it eases the readability of the code: seeing @staticmethod ; we know that the method does not depend on the state of object itself[1].

Class Methods

Class methods are methods that are not bound to an object, but to a class[2]. With class methods the class, not the instance is passed as the implicit first argument.  This means you can use the class and its properties inside that method rather than a particular instance[3].

def a_class_method(cls,x):
return x

The main advantages for using class methods are when using Factory methods, i.e methods that are used to create an instance of a class.
Below is an example. Here you can see that we create 2 separate instances of the Person class. The first via the standard __init__ constructor, and the second using the class method.

class Person:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

@classmethod def from_string(cls, name_string): names = name_string.split() return cls(first_name=names[0], last_name=[1]) >>> p1 = Person('bob','smith') >>> p2 = Person.from_string('dave jones') >>> type(p1) <type 'instance'> >>> type(p2) <type 'instance'> >>> p1.first_name 'bob' >>> p2.first_name 'dave'



Additional Links

Tags: Python