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

Ready to Master Network Automation? Start Your Journey Today!
Our membership provides:
  • Full deep-dive course library (inc. Batfish, pyATS, Netmiko)
  • Code repositories inc. full course code, scripts and examples
  • 24x7 multi-vendor labs (Arista, Cisco, Juniper)
  • Private online community
  • Live monthly tech sessions
  • Access to tech session library

Join Now ➜