码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象——property装饰器

时间:2018-10-24 16:51:08      阅读:206      评论:0      收藏:0      [点我收藏+]

标签: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.__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装饰器

标签:span   作用   BMI   pre   turn   方案   def   elf   div   

原文地址:https://www.cnblogs.com/msj513/p/9844241.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!