Python基礎(七) python自帶的三個裝飾器

說到裝飾器,就不得不說python自帶的三個裝飾器:python

一、@property   將某函數,作爲屬性使用函數

 @property 修飾,就是將方法,變成一個屬性來使用。學習

class A():


    @property
    def pfunc(self):
        return self.value

    @pfunc.setter
    def pfunc(self,value):
        self.value = value

    @property
    def pfunc1(self):
        print('this is property')

if __name__=="__main__":

    A.pfunc = 9
    print A.pfunc
    A.pfunc1

 

二、@classmethod  修飾類的方式this

帶修飾類方法:cls作爲方法的第一個參數,隱式的將類作爲對象,傳遞給方法,調用時無須實例化。spa

普通函數方法:self作爲第一個參數,隱式的將類實例傳遞給方法,調用方法時,類必須實例化。code

class A():
    def func(self,x,y):
        return x * y

    @classmethod
    def cfunc(cls,x,y):
        return x * y
if __name__=="__main__":
    print A().func(5,5)
    print A.cfunc(4,5)

 

三、@staticmethod  修飾類的方式對象

1)是把函數嵌入到類中的一種方式,函數就屬於類,同時代表函數不須要訪問這個類blog

 2)使用修飾服,修飾方法,不須要實例化class

 

class A():
    def func(self,x,y):
        return x * y


    @staticmethod
    def sfunc(x,y):
        return x * y


if __name__=="__main__":

    print A.sfunc(6,5)

 

 

Linux and python學習交流1,2羣已滿.方法

Linux and python學習交流3羣新開,歡迎加入,一塊兒學習.qq 3羣:563227894

不前進,不倒退,中止的狀態是沒有的.

一塊兒進步,與君共勉,

相關文章
相關標籤/搜索