标签:span 作用 BMI pre turn 方案 def elf div
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__)
标签:span 作用 BMI pre turn 方案 def elf div
原文地址:https://www.cnblogs.com/msj513/p/9844241.html