Python staticmethod() Function
staticmethod() is a built-in function in Python used to convert a method into a static method.
A static method belongs to the class rather than to an instance; it does not need to access instance attributes or call instance methods.staticmethod() It can be used as a decorator or called directly.
Word meaning: staticmethod Is static methodis short for (static method).
Basic syntax and parameters
Syntax format
staticmethod(function)
Parameter Description
- Parameter function:
- Type: function object
- Description: the function to convert into a static method.
Function description
- Return Value: Returns a static method object.
- Feature: A static method does not need the
selfparameter and can be called directly through the class name.
Example
Example 1: basic usage
Example
class
MathUtils:
Define a static method with a decorator (recommended)
@
staticmethod
def
add
(
a
,
b
)
:
return
a + b
@
staticmethod
def
multiply
(
a
,
b
)
:
return
a * b
Call it directly through the class name (no instance needed)
result
=
MathUtils.
add
(
3
,
5
)
(
result
)
Output: 8
result
=
MathUtils.
multiply
(
4
,
6
)
(
result
)
Output: 24
Expected output:
8
24
Code analysis:
- Static methods use the
@staticmethoddecorator to be defined. - They can be called like ordinary functions, but belong to the class namespace.
- They can be called without creating an instance of the class.
Example 2: without a decorator
Example
class
Temperature:
@
staticmethod
def
celsius_to_fahrenheit
(
c
)
:
return
c *
9
/
5
32
@
staticmethod
def
fahrenheit_to_celsius
(
f
)
:
return
(
f -
32
)
5
/
9
Call the static method
(
Temperature.
celsius_to_fahrenheit
(
0
)
)
Output: 32.0
(
Temperature.
celsius_to_fahrenheit
(
100
)
)
Output: 212.0
(
Temperature.
fahrenheit_to_celsius
(
32
)
)
Output: 0.0
They can also be called through an instance
temp
=
Temperature
(
)
(
temp.
celsius_to_fahrenheit
(
25
)
)
Output: 77.0
Expected output:
32.0
212.0
0.0
77.0
Code analysis:
- Static methods are often used in utility classes to wrap functions unrelated to instances.
- Static methods can be called through the class name or an instance name.
Example 3: use in the factory pattern
Example
class
Person:
def
init
(
self
,
name
,
age
)
:
self
.
name
=
name
self
.
age
=
age
@
staticmethod
def
from_dict
(
data
)
:
Create a Person object from a dictionary
return
Person
(
data
[
'name'
]
,
data
[
'age'
]
)
@
staticmethod
def
create_adult
(
name
)
:
Create an adult
return
Person
(
name
,
18
)
Create objects using a static method
p1
=
Person.
from_dict
(
{
'name'
:
'Tom'
,
'age'
:
20
}
)
(
p1.
name
,
p1.
age
)
Output: Tom 20
p2
=
Person.
create_adult
(
'Jack'
)
(
p2.
name
,
p2.
age
)
Output: Jack 18
Expected output:
Tom 20
Jack 18
Static methods are often used as factory methods, creating object instances from different data sources.
Python3 built-in function