Python 3.1 快速導覽 - 內建函數 staticmethod()

內建函數 (function) staticmethod() ,回傳參數 (parameter) function 為 static 方法

函數描述
staticmethod(function)回傳 function 為 static 方法


舉例示範如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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 行
11
12
13
14
def statictest():
    print("this is static method..")
     
statictest = staticmethod(statictest)


static 方法 statictest() 定義完後,在底下沒有縮排 (indentation) ,也就是跟 def 具有相同縮排等級的地方,以類別方法的名稱當作參數,呼叫內建函數 staticmethod() ,同時以相同名稱接收回傳值,就可以建立 static 方法。


中英文術語對照
函數function
參數parameter
縮排indentation


內建函數




沒有留言: