Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python staticmethod() Function



ThePython staticmethod() function is abuilt-in function used to convert a given method into a static method. Once the method is converted, it is not bound to an instance of the class but to the class itself.

Like other object-oriented programming languages, Python also has the concept of static methods. This type of methods can be invoked directly without creating an instance of the class.

Syntax

Following is the syntax of the Pythonstaticmethod() function −

staticmethod(nameOfMethod)

Parameters

The Pythonstaticmethod() function accepts a single parameter −

  • nameOfMethod − This parameter represents a method that we want to convert into static.

Return Value

The Pythonstaticmethod() function returns a static method.

staticmethod() Function Examples

Practice the following examples to understand the use ofstaticmethod() function in Python:

Example: Use of staticmethod() Method

The following example shows the usage of Pythonstaticmethod() function. Here, we are creating a method that perform addition of two numbers. And then, we are passing this method along with the class name to the staticmethod() as a parameter value to convert it into astatic method.

class Mathematics:   def addition(valOne, valTwo):      return valOne + valTwoMathematics.addition = staticmethod(Mathematics.addition)output = Mathematics.addition(51, 99)print("The result of adding both numbers:", output)

When we run above program, it produces following result −

The result of adding both numbers: 150

Example: Define Static Method Using @staticmethod Decorator

To define a static method, Python provides another way which is the use of@staticmethod decorator. Below is an example of creating a static method named "subtraction".

class Mathematics:   @staticmethod   def subtraction(valOne, valTwo):      return valOne - valTwooutput = Mathematics.subtraction(99, 55)print("The result of subtracting both numbers:", output)

Following is an output of the above code −

The result of subtracting both numbers: 44

Example: Use of staticmethod() With Utility Functions

In Python, one of the use-case ofstaticmethod() is the utility functions which are a way of implementing common tasks that can be frequently reused. The code below demonstrates how to use the staticmethod() with the utility functions.

class Checker:   @staticmethod   def checking(value):      return isinstance(value, int)print("Is the given number is integer:")print(Checker.checking(142))

Output of the above code is as follows −

Is the given number is integer:True
python_built_in_functions.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp