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

內建函數 (function) classmethod() ,回傳參數 (parameter) function 為類別方法

函數描述
classmethod(function)回傳 function 為類別方法


舉例示範如下
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()

# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:cla13.py
# 功能:示範 Python 程式 
# 作者:張凱慶
# 時間:西元 2010 年 12 月 


執行結果如下



第 16 行到第 20 行
def classtest(cls):
    print("this is class method..")
    print("the class name is", cls.__name__)
    
classtest = classmethod(classtest)


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


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


內建函數




沒有留言: