python之內建裝飾器(property/staticmethod/classmethod)

來源:互聯網
上載者:User

標籤:print   pytho   其他   方法調用   test   簡單   eth   square   ssm   

 

python內建了property、staticmethod、classmethod三個裝飾器,有時候我們也會用到,這裡簡單說明下

 

1、property

作用:顧名思義把函數裝飾成屬性

一般我們調用類方法成員,都是如下寫法:

class propertyTest():    def __init__(self,x,y):        self.x = x        self.y = y    def square(self):        return self.x * self.ypt = propertyTest(3,5)print(pt.square())

這裡一看square就是類的一個方法,但如果把他寫成如下形式,那麼就不確定調用的一定是類方法:

class propertyTest():    def __init__(self,x,y):        self.x = x        self.y = y    @property    def square(self):        return self.x * self.ypt = propertyTest(3,5)print(pt.square)

這裡調用方法類似調用了一個成員變數一樣,如果寫成print(pt.square())編譯器會報錯

這就是property的用法, 把一個方法變成一個變數來調用

 

 

2、staticmethod

作用:不需要執行個體化,直接可以調用類中的方法,如下所示

class A():    def __init__(self):        pass    @staticmethod    def plus(x,y):        print(x*y)c = A()c.plus(2,3)A.plus(4,5)

我們可以執行個體化類A,然後調用方法plus,也可以直接類.方法調用

 

3、classmethod

作用:和staticmethod類似,不同的是把調用的類作為第一個參數傳入,如下:

class A():    def __init__(self):        pass    @classmethod    def plus(cls,x,y):        print(cls)        print(x*y)A.plus(4,5)c = A()c.plus(5,6)

這裡print(cls)列印的是類A,其他用法同staticmethod

 

python之內建裝飾器(property/staticmethod/classmethod)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.