如何在 Python 中建立靜態類資料和靜態類方法?


Python 包含靜態類資料和靜態類方法的概念。

靜態類資料

在這裡,為靜態類資料定義一個類屬性。如果您想為屬性分配新值,請在賦值中顯式使用類名 -

class Demo: count = 0 def __init__(self): Demo.count = Demo.count + 1 def getcount(self): return Demo.count

我們也可以返回以下內容而不是返回 Demo.count -

return self.count

在 Demo 的方法內,類似 self.count = 42 的賦值會在 self 自己的 dict 中建立一個新的、不相關的名為 count 的例項。類靜態資料名稱的重新繫結必須始終指定類,無論是在方法內部還是外部 -

Demo.count = 314

靜態類方法

讓我們看看靜態方法是如何工作的。靜態方法繫結到類而不是類的物件。靜態方法用於建立實用程式函式。

靜態方法不能訪問或修改類狀態。靜態方法不知道類狀態。這些方法用於透過獲取一些引數來執行一些實用程式任務。

請記住,@staticmethod 裝飾器用於建立靜態方法,如下所示 -

class Demo: @staticmethod def static(arg1, arg2, arg3): # No 'self' parameter! ...

示例

讓我們看一個完整的例子 -

from datetime import date class Student: def __init__(self, name, age): self.name = name self.age = age # A class method @classmethod def birthYear(cls, name, year): return cls(name, date.today().year - year) # A static method # If a Student is over 18 or not @staticmethod def checkAdult(age): return age > 18 # Creating 4 objects st1 = Student('Jacob', 20) st2 = Student('John', 21) st3 = Student.birthYear('Tom', 2000) st4 = Student.birthYear('Anthony', 2003) print("Student1 Age = ",st1.age) print("Student2 Age = ",st2.age) print("Student3 Age = ",st3.age) print("Student4 Age = ",st4.age) # Display the result print(Student.checkAdult(22)) print(Student.checkAdult(20))

輸出

Student1 Age =  20
Student2 Age =  21
Student3 Age =  22
Student4 Age =  19
True
True

更新於: 2022-09-19

2K+ 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.