新聞中心
@staticmethod是一個內(nèi)置的裝飾器,它在 Python 的類中定義了一個靜態(tài)方法。 靜態(tài)方法不接收任何引用參數(shù),無論它是由類的實(shí)例調(diào)用還是由類本身調(diào)用。

10年積累的網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)經(jīng)驗(yàn),可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先網(wǎng)站制作后付款的網(wǎng)站建設(shè)流程,更有榕城免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
@staticmethod 特性
- 在類中聲明靜態(tài)方法。
- 它不能有
cls或self參數(shù)。 - 靜態(tài)方法無法訪問類屬性或?qū)嵗龑傩浴?/li>
- 靜態(tài)方法可以使用
ClassName.MethodName()調(diào)用,也可以使用object.MethodName()調(diào)用。 - 它可以返回類的對象。
下面的示例演示如何在類中定義靜態(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參數(shù)。
靜態(tài)方法可以使用ClassName.MethodName()或object.MethodName()調(diào)用,如下圖所示。
Example: Calling Class Method using Object
>>> Student.tostring()
'Student Class'
>>> Student().tostring()
'Student Class'
>>> std = Student()
>>> std.tostring()
'Student Class' 靜態(tài)方法無法訪問類屬性或?qū)嵗龑傩浴H绻麌L試這樣做,將會引發(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) 當(dāng)您調(diào)用上面的靜態(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)方法。 |
| 它可以訪問類屬性,但不能訪問實(shí)例屬性。 | 它不能訪問類屬性或?qū)嵗龑傩浴?/td> |
可以使用ClassName.MethodName()或object.MethodName()來調(diào)用。 |
可以使用ClassName.MethodName()或object.MethodName()來調(diào)用。 |
| 它可以用來聲明返回類對象的工廠方法。 | 它可以返回類的對象。 |
分享標(biāo)題:在Python中使用@staticmethod裝飾器定義靜態(tài)方法
本文來源:http://m.fisionsoft.com.cn/article/djophgs.html


咨詢
建站咨詢
