The staticmethod () function in Python

The function staticmethod () is considered un-Pythonic (Python's unorthodox language). In newer versions of Python, you should use the @staticmethod decorator instead. 

The syntax of @staticmethod is:

@staticmethod def func(args, .)

The syntax of the staticmethod () function in Python

The function staticmethod () is determined by the following syntax:

staticmethod(function)

Parameters of the staticmethod () function

The staticmethod () function has a single parameter:

  1. Function: The function needs to be converted into a static method

The return value of the staticmethod () function

The staticmethod () function returns a static method for a parameter function that you include.

The staticmethod () function in Python Picture 1 The staticmethod () function in Python is used to create static methods of an object

What is static method?

Static methods, like class methods, are methods that are associated with a class and not its objects. Static methods have the advantage of not depending on the state of the object.

The difference between a static method and a class method is:

The static method knows nothing about the class and only processes parameters. Meanwhile, the class method is always based on the class because its parameter is always the class itself. 

Both static methods and class methods can be called by both classes and objects.

Class.staticmethodFunc() or even Class().staticmethodFunc()

Example 1: Create a static method using the staticmethod () function

class Tipsmake: def addnumbers(x, y): return x + y # make static method add numbers Tipsmake.addnumbers = staticmethod(Tipsmake.addnumbers) print('The total is:', Tipsmake.addnumbers(5, 10))

When running the program, the result is:

The total is : 15

When should we use static methods?

1. Group utility functions into a class

The applicability of static methods is quite limited because, like the class method or any method within the class, they cannot access the properties of the class itself.

However, when you need a utility function that does not access any properties of a class but makes sense that it belongs to that class, we will use the static method.

Example 2: Creating a utility function using static methods

class Dates: def __init__(self, date): self.date = date def getDate(self): return self.date @staticmethod def toDashDate(date): return date.replace("/", "-") date = Dates("15-12-2016") dateFromDB = "15/12/2016" dateWithDash = Dates.toDashDate(dateFromDB) if(date.getDate() == dateWithDash): print("Match") else: print("Not Match")

Running the program results in:

Match

Here, we have the Dates class which only works with the date data using dashes to indicate. However, in the old data, all dates use slashes to indicate.

To convert a date using a slash to a date using a hyphen, we create a utility function toDashDate inside Dates .

It is a static method because it does not need to access any of the properties of Dates and requires only input parameters.

We can also create toDashDate outside of the class but since it only processes data related to dates, leaving it in the Dates class is a logical choice, helping the code to be cleaner.

2. There is only one executable

Static methods are used when we do not want a subclass in a class to change / override a special implementation of a method.

Example 3: How does inheritance work with static methods?

class Dates: def __init__(self, date): self.date = date def getDate(self): return self.date @staticmethod def toDashDate(date): return date.replace("/", "-") class DatesWithSlashes(Dates): def getDate(self): return Dates.toDashDate(self.date) date = Dates("15-12-2016") dateFromDB = DatesWithSlashes("15/12/2016") if(date.getDate() == dateFromDB.getDate()): print("Match") else: print("Not Match")

Result

Match

Here, we do not want the subclasses DatesWithSlashes to override static utility method toDashDate because it is only used once, for example changing the date from the form using the slash to the form of dash.

We can easily use the static method to get more benefits by overriding the getDate () method in the subclass so it works well with the DatesWithSlashes class .

  1. Python functions built in
  2. If, if . else, if . elif . else statements in Python
  3. Data types in Python: string, number, list, tuple, set and dictionary
5 ★ | 1 Vote

May be interested

  • The function set () in PythonThe function set () in Python
    in this article, tipsmake.com will learn with you about set (), syntax, parameters and specific examples. invites you to read the track.
  • Help () function in PythonHelp () function in Python
    the built-in help () function in python is used to display documents and invoke the help system of modules, functions, classes, keywords ...
  • Sum () function in PythonSum () function in Python
    the built-in function sum () in python returns the sum of all numbers in iterable.
  • The slice () function in PythonThe slice () function in Python
    the slice () function in python returns a slice object that helps you determine how to cut an existing string.
  • The chr () function in PythonThe chr () function in Python
    in python, the chr () function returns a character (a string) from an integer that represents the unicode of the returned character.
  • The iter () function in PythonThe iter () function in Python
    continuing with the topic of python's built-in functions, the article will introduce you to the iter () function with the syntax, usage as well as specific examples. invites you to read the track.
  • The pow () function in PythonThe pow () function in Python
    the pow () function built into python returns the value of x with the power of y (xy). if there is a third parameter, the function returns x to the power y, the module z.
  • The reversed () function in PythonThe reversed () function in Python
    the reversed () function is one of the built-in functions in python, used to reverse the original string returning the iterator.
  • Exec () function in PythonExec () function in Python
    the exec () function used to execute python programs dynamically can be string or object code. how does exec () function syntax, what parameters do it have, and how is it used? invites you to read the track.
  • Built-in Python functionsBuilt-in Python functions
    in the previous article, you learned that python has a basic function type, one is a built-in function, two are user-defined functions. today, we will learn about a list of python's built-in functions.