Static Method Decorator
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 11 of 64.
The @staticmethod decorator creates methods that don't need self or the class. They work like regular functions but belong to the class.
Here is an example of a class with static methods:
class MathHelper:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def is_even(number):
return number % 2 == 0Call static methods using the class name:
result = MathHelper.add(5, 3)
print(result)
check = MathHelper.is_even(10)
print(check)You can also call them from an object:
helper = MathHelper()
result2 = helper.add(2, 4)
print(result2)Output:
8
True
6Static methods don't access instance or class data:
class Calculator:
brand = "Python Calc"
def __init__(self, owner):
self.owner = owner
@staticmethod
def multiply(x, y):
# Cannot access self.owner or Calculator.brand
return x * yKey Point: Use @staticmethod when you need a function that's related to the class but doesn't need access to instance (self) or class data. No self parameter needed.
Cheat sheet
The @staticmethod decorator creates methods that don't need self or the class. They work like regular functions but belong to the class.
class MathHelper:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def is_even(number):
return number % 2 == 0Call static methods using the class name:
result = MathHelper.add(5, 3)
check = MathHelper.is_even(10)You can also call them from an object:
helper = MathHelper()
result2 = helper.add(2, 4)Static methods don't access instance or class data - no self parameter needed.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes