python 类方法,和实例方法

 
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



 



 


 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值