物件導向——property裝飾器

來源:互聯網
上載者:User

標籤:span   作用   BMI   pre   turn   方案   def   elf   div   

property裝飾器

property裝飾器的作用,其實就是將將函數屬性偽裝成為屬性的的裝飾器

class People:    def __init__(self,name,weight,height):        self.name = name        self.weight =weight        self.height=height    @property    def bmi(self):        return self.weight/(self.height**2)msj = People(‘msj‘,82,1.84)print(msj.bmi)#24.22022684310019

但是這這隻是偽裝成屬性的,修改並不像屬性一樣能被修改

解決方案一:

class People:    def __init__(self,name,weight,height):        self.name = name        self.__weight =weight        self.__height=height    #介面顯示身高    @property    def height(self):         print(self.__height)    #介面修改身高屬性    @height.setter    def height(self,h):        self.__height = h    #介面刪除身高屬性    @height.deleter    def height(self):        del self.__heightp2 = People(‘egon‘,70,182)p2.heightp2.height=183p2.heightdel p2.heightprint(p2.__dict__)“”“182183{‘name‘: ‘egon‘, ‘_People__weight‘: 70}”“”

方案二

class People:    def __init__(self,name,weight,height):        self.name = name        self.__weight =weight        self.__height=height    #介面顯示身高    def tell_height(self):         print(self.__height)    #介面修改身高屬性    def set_height(self,h):        self.__height = h    #介面刪除身高屬性    def del_height(self):        del self.__height    height = property(tell_height,set_height,del_height)p2 = People(‘egon‘,70,182)p2.heightp2.height=183p2.heightdel p2.heightprint(p2.__dict__)

 

物件導向——property裝飾器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.