面向对象——property装饰器
Posted msj513
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面向对象——property装饰器相关的知识,希望对你有一定的参考价值。
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装饰器的主要内容,如果未能解决你的问题,请参考以下文章