Static method can be called without creating an object or instance. Simply create the method and call it directly. This is in a sense orthogonal to object orientated programming: we call a method without creating objects.

This runs directly against the concept of object oriented programming and might be frowned upon, but at times it can be useful to have a static method.

Related course: Complete Python Programming Course & Exercises

Example

Static method

Normally you'd want to either have function calls, or to create an object on which you call its methods. You can however do something else: call a method in a class without creating an object.

Demonstration of static method below. Define a class with a method. Add the keyword @staticmethod above it to make it static.

1
2
3
4
5
6
class Music:
@staticmethod
def play():
print("*playing music*")

Music.play()

Static-methods inside a class

A class can contain both static and non-static methods. If you want to call non-static methods, you'll have to create an object. The code below does not work because an object is not created:

1
2
3
4
5
6
7
8
9
10
class Music:
@staticmethod
def play():
print("*playing music*")

def stop(self):
print("stop playing")

Music.play()
Music.stop()

Calling static methods

Normal class methods and static methods can be mixed (because why not?).
This can get very confusing: we use both the concept of object orientation and functional programming mixed in one class.

If you create an object, we can call non-static methods. But you can also call the static method without creating the object.

1
2
3
4
5
6
7
8
9
10
11
12
class Music:
@staticmethod
def play():
print("*playing music*")

def stop(self):
print("stop playing")

Music.play()

obj = Music()
obj.stop()

Overall, static methods are an interesting concept to know, but in practice you'd rarely use them. Sometimes using static methods could be an indication of having a bad design.

If you are a beginner, then I highly recommend this YouTube Python Playlist.

Exercise

Try the exercises below

  • Can a method inside a class be called without creating an object?
  • Why does not everybody like static methods?

After completing these continue with the next exercise.