首頁  >  文章  >  後端開發  >  如何在Python中建立靜態類別資料和靜態類別方法?

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

WBOY
WBOY轉載
2023-09-07 22:13:02703瀏覽

如何在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 自己的字典中建立一個名為 count 的新的、不相關的實例。類別靜態資料名稱的重新綁定必須始終指定類,無論是否在方法內部 -

Demo.count = 314

靜態類別方法

讓我們看看靜態方法是如何運作的。靜態方法綁定到類別而不是類別的物件。 statis 方法用於建立實用函數。

靜態方法無法存取或修改類別狀態。靜態方法不知道類別狀態。這些方法用於透過獲取一些參數來執行一些實用任務。

請記住,@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

以上是如何在Python中建立靜態類別資料和靜態類別方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除