fir3net
PPS-Firenetbanner-780.5x190-30-03-17

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.

...
@staticmethod
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].

...
@classmethod
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'

Sources

[1] http://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner
[2] https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods
[3] http://python-reference.readthedocs.io/en/latest/docs/classmethod/

Additional Links

https://teamtreehouse.com/community/classmethod

Tags: Python

About the Author

RDonato

R Donato

Rick Donato is the Founder and Chief Editor of Fir3net.com. He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001