1. 程式人生 > >面向對象——property裝飾器

面向對象——property裝飾器

int prope tel print delete 裝飾 函數 面向對象 但是

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.__height p2 = People(egon,70,182) p2.height p2.height=183 p2.height del p2.height print(p2.__dict__) “”“ 182 183 {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.height p2.height=183 p2.height del p2.height print(p2.__dict__)

面向對象——property裝飾器