如何在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中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Linux終端中查看Python版本時遇到權限問題的解決方法當你在Linux終端中嘗試查看Python的版本時,輸入python...

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

在使用Python的pandas庫時,如何在兩個結構不同的DataFrame之間進行整列複製是一個常見的問題。假設我們有兩個Dat...

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

Uvicorn是如何持續監聽HTTP請求的? Uvicorn是一個基於ASGI的輕量級Web服務器,其核心功能之一便是監聽HTTP請求並進�...

攻克Investing.com的反爬蟲策略許多人嘗試爬取Investing.com(https://cn.investing.com/news/latest-news)的新聞數據時,常常�...
