Python 類別 (class) 的方法 (method) 除了實體方法外,還有 static 方法與類別方法。
static 方法的作用與函數 (function) 相同,也就是說不需要建立實體物件 (instance) 就可以使用,然而 static 方法仍是類別的一部分,因此呼叫 (call) 類別方法需連用類別名稱。
類別方法需要一個特別的參數 (parameter) ,習慣上使用 cls ,這與實體方法的 self 類似,不同的是 cls 用來存取類別的屬性 (attribute) 。
class
Demo:
def
__init__(
self
, i):
self
.i
=
i
def
__str__(
self
):
return
str
(
self
.i)
def
hello(
self
):
print
(
"hello"
,
self
.i)
def
statictest():
print
(
"this is static method.."
)
statictest
=
staticmethod
(statictest)
def
classtest(
cls
):
print
(
"this is class method.."
)
print
(
"the class name is"
,
cls
.__name__)
classtest
=
classmethod
(classtest)
Demo.statictest()
Demo.classtest()
print
()
a
=
Demo(
9527
)
a.hello()
a.statictest()
a.classtest()
# 《程式語言教學誌》的範例程式
# 檔名:cla13.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月
第 11 行到第 14 行
def
statictest():
print
(
"this is static method.."
)
statictest
=
staticmethod
(statictest)
這裡定義 statictest() 方法,注意此例提供的 static 方法沒有參數。在 static 方法定義完後,在底下沒有縮排 (indentation) ,也就是跟 def 具有相同縮排等級的地方,以 static 方法的名稱當作參數,呼叫內建函數 staticmethod() ,同時以相同名稱接收回傳值,就可以建立 static 方法。
def
classtest(
cls
):
print
(
"this is class method.."
)
print
(
"the class name is"
,
cls
.__name__)
classtest
=
classmethod
(classtest)
這裡定義的 classtest() 為類別方法,其後呼叫內建函數 classmethod() 的方式與 staticmethod() 一樣。
另一種利用修飾符號 @ ,如下例
class
Demo:
def
__init__(
self
, i):
self
.i
=
i
def
__str__(
self
):
return
str
(
self
.i)
def
hello(
self
):
print
(
"hello"
,
self
.i)
@staticmethod
def
statictest():
print
(
"this is static method.."
)
@classmethod
def
classtest(
cls
):
print
(
"this is class method.."
)
print
(
"the class name is"
,
cls
.__name__)
Demo.statictest()
Demo.classtest()
print
()
a
=
Demo(
9527
)
a.hello()
a.statictest()
a.classtest()
# 《程式語言教學誌》的範例程式
# 檔名:cla14.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月
|
利用修飾符號 @ ,無須額外呼叫內建函數,只需要在方法定義前註明是哪一種即可。
需要注意的是可利用類別名稱呼叫 static 方法與類別方法,也可以利用實體物件呼叫兩者,但若沒有呼叫內建函數或是利用修飾符號 @ 標記,執行時直譯器會不知道是那一種,因此有可能執行時會出錯
中英文術語對照 | |
---|---|
類別 | class |
方法 | method |
函數 | function |
實體物件 | instance |
呼叫 | call |
參數 | parameter |
屬性 | attribute |
縮排 | indentation |
參考資料
http://docs.python.org/py3k/tutorial/classes.html
http://docs.python.org/py3k/reference/compound_stmts.html
http://docs.python.org/py3k/tutorial/classes.html
http://docs.python.org/py3k/reference/compound_stmts.html