Python 中的靜態

靜態變量和靜態方法是 C++ 、 PHP 、 Java 等多種語言中廣泛使用的編程概念。這些變量和方法屬於類和對象。在本節中,我們將學習如何在 Python 中創建靜態變量和方法。

Python 靜態變量

當我們在類內部聲明一個變量,但在方法外部聲明時,它被稱為靜態或類變量。它可以直接從類中調用,但不能通過類的實例調用。然而,靜態變量與其他成員有很大不同,它與 Python 程序中的相同變量名並不衝突。

讓我們考慮一個程序來演示靜態變量在 Python 中的使用。

Static.py


class Employee: # create Employee class name
    dept = 'Information technology'  # define class variable
    def __init__(self, name, id):
        self.name = name       # instance variable
        self.id = id             # instance variable

# Define the objects of Employee class
emp1 = Employee('John', 'E101')        
emp2 = Employee('Marcus', 'E105')

print (emp1.dept) 
print (emp2.dept) 
print (emp1.name) 
print (emp2.name) 
print (emp1.id)  
print (emp2.id) 

# Access class variable using the class name
print (Employee.dept) # print the department

# change the department of particular instance
emp1.dept = 'Networking'
print (emp1.dept) 
print (emp2.dept) 

# change the department for all instances of the class
Employee.dept = 'Database Administration'
print (emp1.dept) 
print (emp2.dept)

輸出:

Information technology
Information technology
John
Marcus
E101
E105
Information technology
Networking
Information technology
Networking
Database Administration

在上面的例子中, dept 是在類方法外部和類定義內部定義的類變量。其中名稱和 id 是在方法內部定義的實例變量。

使用相同的類對象訪問靜態變量

我們可以使用帶有點運算符的同一個類對象直接訪問 Python 中的靜態變量。

讓我們考慮一個使用相同類對象訪問 Python 中靜態變量的程序。

static CVaR . py


class Car:
    # define the class variable or static variable of class Car
    num = 7
    msg = 'This is a good Car.'

# create the object of the class
obj = Car()

# Access a static variable num using the class name with a dot operator.
print ("Lucky No.", Car.num)
print (Car.msg)

輸出:

Lucky No. 7
This is a good Car

靜態法

Python 有一個屬於類的靜態方法。它就像一個靜態變量,綁定到類而不是類的對象。可以在不為類創建對象的情況下調用靜態方法。這意味着我們可以直接用類名的引用來調用靜態方法。此外,靜態方法受類的約束;因此,它不能改變對象的狀態。

靜態方法的特點

靜態方法的特徵如下:

  1. Python 中與類相關的靜態方法。
  2. 它可以通過引用類名直接從類中調用。
  3. 它不能訪問 Python 程序中的類屬性。
  4. 它只綁定到類。所以它不能修改對象的狀態
  5. 它還用於劃分類的實用方法。
  6. 它只能在類內部定義,不能定義到類的對象。
  7. 該類的所有對象只共享靜態方法的一個副本。

在 Python 中定義靜態方法有兩種方法:

  1. 使用靜態方法()方法
  2. 使用@staticmethod 裝飾器

使用靜態方法()方法

A staticmethod ()是 Python 中的內置函數,用於將給定函數作為靜態方法返回。

語法:


staticmethod (function)

A staticmethod ()取單個參數。其中傳遞的參數是需要轉換為靜態方法的函數。

讓我們考慮一個程序,使用 Python 中的 static method()創建一個函數作為靜態方法。

靜態方法. py


class Marks:
    def Math_num(a, b): # define the static Math_num() function
        return a + b

    def Sci_num(a, b): # define the static Sci_num() function
        return a +b

    def Eng_num(a, b):  # define the static Eng_num() function
        return a +b
# create Math_num as static method
Marks.Math_num = staticmethod(Marks.Math_num)

# print the total marks in Maths
print (" Total Marks in Maths" , Marks.Math_num(64, 28)) 

# create Sci_num as static method
Marks.Sci_num = staticmethod(Marks.Sci_num)

# print the total marks in Science
print (" Total Marks in Science" , Marks.Sci_num(70, 25)) 

# create Eng_num as static method
Marks.Eng_num = staticmethod(Marks.Eng_num)

# print the total marks in English
print (" Total Marks in English" , Marks.Eng_num(65, 30))

輸出:

Total Marks in Maths 92
 Total Marks in Science 95
 Total Marks in English 95

在上面的程序中,我們使用 staticmethod() 函數將 Math_num 方法、Sci_num 方法和 Eng_num 方法聲明為類外的靜態方法。之後,我們可以直接使用類名標記來調用靜態方法。

使用@staticmethod 裝飾器

@staticmethod 是一個內置的裝飾器,它定義了類內部的靜態方法。它不會接收任何參數作為對類實例或調用靜態方法本身的類的引用。

語法:


class Abc:
@staticmethod
def function_name (arg1, arg2, ?):
# Statement to be executed
Returns: a static method for function function_name

注意:一個@staticmethod 是一種將方法定義為靜態方法的現代方法,大多數程序員在 Python 編程中都使用這種方法。

讓我們創建一個程序,使用 Python 中的@staticmethod 裝飾器來定義靜態方法。

靜安定劑. py


class Marks:
    @staticmethod
    def Math_num(a, b): # define the static Math_num() function
        return a + b

    @staticmethod
    def Sci_num(a, b): # define the static Sci_num() function
        return a +b

    @staticmethod
    def Eng_num(a, b):  # define the static Eng_num() function
        return a +b

# print the total marks in Maths
print (" Total Marks in Maths" , Marks.Math_num(64, 28)) 

# print the total marks in Science
print (" Total Marks in Science" , Marks.Sci_num(70, 25))

# print the total marks in English
print (" Total Marks in English" , Marks.Eng_num(65, 30))

輸出:

Total Marks in Maths 92
 Total Marks in Science 95
 Total Marks in English 95

使用相同的類對象訪問靜態方法

考慮一個使用 Python 中的@staticmethod 訪問類的靜態方法的程序。

測試 py


class Test:
    # define a static method using the @staticmethod decorator in Python.
    @staticmethod
    def beg():
        print ("Welcome to the World!! ")

# create an  object of the class Test
obj = Test()
# call the static method 
obj.beg()

輸出:

Welcome to the World!!

函數使用靜態方法返回值

讓我們編寫一個程序,使用 Python 中的@staticmethod 返回值。

Static_method.py


class Person: 
    @staticmethod
    def Age (age):
        if (age <= 18): # check whether the Person is eligible to vote or not.
            print ("The person is not eligible to vote.")
        else:
            print ("The person is eligible to vote.")

Person.Age(17) 

輸出:

The person is not eligible to vote.

原創文章,作者:SE405,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/127885.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
SE405的頭像SE405
上一篇 2024-10-03 23:16
下一篇 2024-10-03 23:16

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29

發表回復

登錄後才能評論