⬅ Previous Topic
Python sorted() Function – Sort Any Iterable EasilyNext Topic ⮕
Python str() Function – Convert to String Easily⬅ Previous Topic
Python sorted() Function – Sort Any Iterable EasilyNext Topic ⮕
Python str() Function – Convert to String Easilystaticmethod()
FunctionThe staticmethod() function in Python is used to define a static method inside a class. A static method doesn't take the instance (self
) or class (cls
) as the first argument. It behaves like a regular function but belongs to the class’s namespace.
staticmethod(function)
function
– A function you want to convert into a static method.class MathUtils:
@staticmethod
def add(a, b):
return a + b
# Call without creating an object
print(MathUtils.add(5, 3))
8
You can also use staticmethod()
without the @staticmethod
decorator:
class MathUtils:
def add(a, b):
return a + b
add = staticmethod(add)
print(MathUtils.add(10, 4))
14
staticmethod()
?Feature | staticmethod() | classmethod() |
---|---|---|
Access to instance? | No | No |
Access to class? | No | Yes |
First argument | None | cls |
Use case | Helper functions | Factory methods |
self
or cls
inside a static method – it won’t work.@staticmethod
decorator or staticmethod()
function – method acts as a normal one and expects self
.Interviewers often ask the difference between staticmethod()
and classmethod()
. Know when and why to use each.
staticmethod()
makes a function callable via the class without needing an object.Create a class Temperature
with a static method celsius_to_fahrenheit(c)
that converts Celsius to Fahrenheit.
class Temperature:
@staticmethod
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
print(Temperature.celsius_to_fahrenheit(37))
98.6
⬅ Previous Topic
Python sorted() Function – Sort Any Iterable EasilyNext Topic ⮕
Python str() Function – Convert to String EasilyYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.