DEV Community

Adam Lombard
Adam Lombard

Posted on • Edited on

Python: class vs. instance vs. static methods

In Python, a method provides functionality to a Class.

There are, broadly, three types of methods:

  • Class Methods : Provide functionality to a class itself
  • Instance Methods : Provide functionality to one instance of a class
  • Static Methods : Provide functionality that can be accessed from a class or from one instance of a class

Consider the following Python class, which defines a Person object and the methods which allow that object to say "hello":

class Person():
  # (Discussing __init__ is beyond the scope of this
  # tutorial)
  def __init__(self, first_name):
    self.first_name = first_name

  # Instance methods are the default method type in a
  # class definition. They receive the class instance
  # itself as their first argument. By convention, 
  # the parameter for this argument is labeled 'self'.
  def say_hi_from_an_instance(self):
    print(f"Hello! My name is {self.first_name}.")

  # Class methods are defined using a special
  # decorator, and receive the class as the first
  # argument. By convention, the parameter for this
  # argument is labeled 'cls'.
  @classmethod
  def say_hi_from_the_class(cls):
    print(f"Hello! I am a {cls.__name__}.")

  # Static methods are defined using a special
  # decorator. They are available on the class and on
  # instances of the class.
  @staticmethod
  def say_hi_from_anywhere():
    print("Why, hello!!!")

Enter fullscreen mode Exit fullscreen mode

Now, from the class:

# We can call the class method greeting
> Person.say_hi_from_the_class()
Hello! I am a Person.

# But we cannot call the instance method greeting
> Person.say_hi_from_an_instance()
Traceback ...
TypeError: say_hi_from_an_instance() missing 1 required positional argument: 'self'
Enter fullscreen mode Exit fullscreen mode

While, from an instance of the class:

> a_person = Person('Louise')

# We can call the instance method greeting
> a_person.say_hi_from_an_instance()
Hello! My name is Louise.

# And we can still call the class method greeting
> a_person.say_hi_from_the_class()
Hello! I am a Person.
Enter fullscreen mode Exit fullscreen mode

Static methods are available on both classes and class instances. They are intended to provide functionality that does not rely on the class or instance itself:

> Person.say_hi_from_anywhere()
Why, hello!!!
> a_person.say_hi_from_anywhere()
Why, hello!!!
Enter fullscreen mode Exit fullscreen mode

See also: Ruby: class methods vs. instance methods


Was this helpful? Did I save you some time?

🫖 Buy Me A Tea! ☕️


Top comments (0)