python @classmethod 和 @staticmethod区别,以及类中方法参数cls和self的区别
生活随笔
收集整理的這篇文章主要介紹了
python @classmethod 和 @staticmethod区别,以及类中方法参数cls和self的区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、@classmethod 和 @staticmethod
1、staticmethod
作用:讓類中的方法變成一個普通函數(普通函數沒有綁定在任何一個特定的類或者實例上。所以與不需要對象實例化就可以直接調用)
特點:既可以使用類直接調用,也可以類的實例調用,并且沒有任何隱含參數的傳入,所以不需要self(參數名是隨便定的)。
>>> class C(object): ... @staticmethod ... def add(a,b): ... return a+b ... def get_weight(self): ... return self.add(1,2) ... >>> C.add <function add at 0x1d32668> >>> C().add <function add at 0x1d32668> >>> C.get_weight <unbound method C.get_weight>2、classmethod
?
二、類中方法參數cls和self的區別
?
?
總結
以上是生活随笔為你收集整理的python @classmethod 和 @staticmethod区别,以及类中方法参数cls和self的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: InnoDB中一棵B+树能存多少行数据
- 下一篇: 双指针相关算法