CodeBlanks Logo Icon CodeBlanks

@staticmethod

Learn static methods with @staticmethod.

The @staticmethod decorator

The @staticmethod decorator defines a method without a self or cls parameter. It is like a regular function placed inside a class.

Example: class Math:\n @staticmethod\n def square(x):\n return x * x. Calling Math.square(5) returns 25; no instance is needed. This is useful for helpers that belong to the class logically but do not need instance data.

Call via the class

Static methods are called on the class without creating an instance. Writing Math.square(5) is enough. They can also be called via an instance, but the class name is more common.

This is practical for grouping helper calculation functions. Example: Math.square(5) and Math.cube(3) live in the same class. Since no instance data is needed at call time, creating an instance would be wasteful.

Practice Add a static method to Math

Define a class named Math. Add the @staticmethod decorator and a method def square(x):; in the body write return x * x. Then call print(Math.square(5)).

Starter code

main.py
# Define the Math class

Sample solution

main.py
# Define the Math class
class Math:
    @staticmethod
    def square(x):
        return x * x

print(Math.square(5))

Expected output

25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which decorator does not require self on a method?

  • @dataclass
  • @classmethod
  • @property
  • @staticmethod Correct answer

Explanation: @staticmethod does not require a self or cls parameter.

2 Complete the static method line

Question
class Math:
    ____
    def square(x):
        return x * x
Answer
class Math:
    @staticmethod
    def square(x):
        return x * x

Explanation: @staticmethod marks the method as a plain function.

3 Match the static method parts

Term Meaning
@staticmethod Decorator
def square(x) Selfless signature
Math.square(5) Call via class

All lessons in Intermediate