新聞中心
這里有您想知道的互聯(lián)網營銷解決方案
在Python中使用@staticmethod裝飾器定義靜態(tài)方法
@staticmethod是一個內置的裝飾器,它在 Python 的類中定義了一個靜態(tài)方法。 靜態(tài)方法不接收任何引用參數,無論它是由類的實例調用還是由類本身調用。

10年積累的網站設計、成都網站建設經驗,可以快速應對客戶對網站的新想法和需求。提供各種問題對應的解決方案。讓選擇我們的客戶得到更好、更有力的網絡服務。我雖然不認識你,你也不認識我。但先網站制作后付款的網站建設流程,更有榕城免費網站建設讓你可以放心的選擇與我們合作。
@staticmethod 特性
- 在類中聲明靜態(tài)方法。
- 它不能有
cls或self參數。 - 靜態(tài)方法無法訪問類屬性或實例屬性。
- 靜態(tài)方法可以使用
ClassName.MethodName()調用,也可以使用object.MethodName()調用。 - 它可以返回類的對象。
下面的示例演示如何在類中定義靜態(tài)方法:
Example: Define Static Method
class Student:
name = 'unknown' # class attribute
def __init__(self):
self.age = 20 # instance attribute
@staticmethod
def tostring():
print('Student Class') 上面,Student類使用@staticmethod裝飾器將tostring()方法聲明為靜態(tài)方法。 注意不能有self或cls參數。
靜態(tài)方法可以使用ClassName.MethodName()或object.MethodName()調用,如下圖所示。
Example: Calling Class Method using Object
>>> Student.tostring()
'Student Class'
>>> Student().tostring()
'Student Class'
>>> std = Student()
>>> std.tostring()
'Student Class' 靜態(tài)方法無法訪問類屬性或實例屬性。如果嘗試這樣做,將會引發(fā)錯誤。
Example: Static Method
class Student:
name = 'unknown' # class attribute
def __init__(self):
self.age = 20 # instance attribute
@staticmethod
def tostring():
print('name=',name,'age=',self.age) 當您調用上面的靜態(tài)方法時,下面將是輸出。
>>> Student.tostring()
Traceback (most recent call last):
File "", line 1, in
Student.tostring()
File "", line 7, in display
print('name=',name,'age=',self.age)
NameError: name 'name' is not defined @classmethod vs @staticmethod
下表列出了類方法與靜態(tài)方法的區(qū)別:
| @classmethod | @staticmethod |
|---|---|
| 聲明一個類方法。 | 聲明一個靜態(tài)方法。 |
| 它可以訪問類屬性,但不能訪問實例屬性。 | 它不能訪問類屬性或實例屬性。 |
可以使用ClassName.MethodName()或object.MethodName()來調用。 |
可以使用ClassName.MethodName()或object.MethodName()來調用。 |
| 它可以用來聲明返回類對象的工廠方法。 | 它可以返回類的對象。 |
新聞標題:在Python中使用@staticmethod裝飾器定義靜態(tài)方法
瀏覽地址:http://www.dlmjj.cn/article/djophgs.html


咨詢
建站咨詢
