Python staticmethod() 函式



Python staticmethod() 函式是用於將給定方法轉換為靜態方法的內建函式。轉換後,該方法不再繫結到類的例項,而是繫結到類本身。

與其他面向物件程式語言一樣,Python 也具有靜態方法的概念。這種型別的方法可以在不建立類例項的情況下直接呼叫。

語法

以下是 Python staticmethod() 函式的語法:

staticmethod(nameOfMethod)

引數

Python staticmethod() 函式接受一個引數:

  • nameOfMethod - 此引數表示我們要轉換為靜態的方法。

返回值

Python staticmethod() 函式返回一個靜態方法。

staticmethod() 函式示例

練習以下示例以瞭解如何在 Python 中使用 staticmethod() 函式

示例:使用 staticmethod() 方法

以下示例演示了 Python staticmethod() 函式的使用。在這裡,我們建立一個執行兩個數字加法的方法。然後,我們將此方法與類名一起作為引數值傳遞給 staticmethod(),以將其轉換為靜態方法

class Mathematics:
   def addition(valOne, valTwo):
      return valOne + valTwo

Mathematics.addition = staticmethod(Mathematics.addition)
output = Mathematics.addition(51, 99)
print("The result of adding both numbers:", output)

執行以上程式時,會產生以下結果:

The result of adding both numbers: 150

示例:使用 @staticmethod 裝飾器定義靜態方法

要定義靜態方法,Python 提供了另一種方法,即使用 @staticmethod 裝飾器。下面是建立名為“subtraction”的靜態方法的示例。

class Mathematics:
   @staticmethod
   def subtraction(valOne, valTwo):
      return valOne - valTwo

output = Mathematics.subtraction(99, 55)
print("The result of subtracting both numbers:", output)

以下是上述程式碼的輸出:

The result of subtracting both numbers: 44

示例:將 staticmethod() 與實用程式函式一起使用

在 Python 中,staticmethod() 的用例之一是實用程式函式,它們是實現可頻繁重複使用的常見任務的一種方法。以下程式碼演示瞭如何將 staticmethod() 與實用程式函式一起使用。

class Checker:
   @staticmethod
   def checking(value):
      return isinstance(value, int)

print("Is the given number is integer:")
print(Checker.checking(142))

上述程式碼的輸出如下:

Is the given number is integer:
True
python_built_in_functions.htm
廣告