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...
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.
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.
Class methods are methods that are not bound to an object, but to a class. 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.
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, last_name=) >>> 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'