@staticmethod
是一個內置的裝飾器,它在 Python 的類中定義了一個靜態方法。 靜態方法不接收任何引用參數,無論它是由類的實例調用還是由類本身調用。
@staticmethod 特性
- 在類中聲明靜態方法。
- 它不能有
cls
或self
參數。 - 靜態方法無法訪問類屬性或實例屬性。
- 靜態方法可以使用
ClassName.MethodName()
調用,也可以使用object.MethodName()
調用。 - 它可以返回類的對象。
下面的示例演示如何在類中定義靜態方法:
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()
方法聲明為靜態方法。 注意不能有self
或cls
參數。
靜態方法可以使用ClassName.MethodName()
或object.MethodName()
調用,如下圖所示。
Example: Calling Class Method using Object
>>> Student.tostring()
'Student Class'
>>> Student().tostring()
'Student Class'
>>> std = Student()
>>> std.tostring()
'Student Class'
靜態方法無法訪問類屬性或實例屬性。如果嘗試這樣做,將會引發錯誤。
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)
當您調用上面的靜態方法時,下面將是輸出。
>>> Student.tostring()
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
Student.tostring()
File "<pyshell#21>", line 7, in display
print('name=',name,'age=',self.age)
NameError: name 'name' is not defined
@classmethod vs @staticmethod
下表列出了類方法與靜態方法的區別:
@classmethod | @staticmethod |
---|---|
聲明一個類方法。 | 聲明一個靜態方法。 |
它可以訪問類屬性,但不能訪問實例屬性。 | 它不能訪問類屬性或實例屬性。 |
可以使用ClassName.MethodName() 或object.MethodName() 來調用。 |
可以使用ClassName.MethodName() 或object.MethodName() 來調用。 |
它可以用來聲明返回類對象的工廠方法。 | 它可以返回類的對象。 |