← All lessons

@staticmethod: a method without an object

Sign in · Sign up

Lesson 10.12

Not every method needs an object. @staticmethod keeps a function inside a class, but no self is passed to it:

class Hero:
    @staticmethod
    def is_valid(name):
        return len(name) >= 2

Hero.is_valid("Mia")
  • @staticmethod goes on the line above def, and there is no self among the parameters;
  • it is called through the class: Hero.is_valid(...) — no object needed for that;
  • this is logic tied to the class: checking rules, converting units, counting.

The check gives the list of names names. For each one print Valid or Too short, checking the name with the static method is_valid.

Hint

The line @staticmethod goes above def, and there is no self among the parameters.

The condition is len(name) >= 2. The call goes through the class: Hero.is_valid(...), and the result decides what to print.