Python - What are Static and Class Methods?

Python - What are Static and Class Methods?

Have you ever seen some Python code and wondered what @staticmethod and @classmethod do ?

Well, let me explain ...

@staticmethod

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 do_something(x):
       return x

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

@classmethod

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. For example, this allows you to create class instantiations within your class, making @classmethod ideal when creating factory methods.

class MyClass(object):
     def __init__(self, x, y):
          pass

     @classmethod
     def do_something(cls, z):
          x, y = map(str, z.split(' '))
          return cls(x, y)

>>> MyClass.do_something('Juniper SRX')
<__main__.MyClass object at 0x7fc523012050>

https://teamtreehouse.com/community/classmethod

Subscribe to our newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox.
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!