property特性

什么是property

property是一种特殊属性,访问他时会执行一段功能然后返回值

class People:
def __init__(self,name,weight,height):
self.name=name
self.weight=weight
self.height=height

@property           #不加property 调用的是一个函数 print(p.bmi())
    def bmi(self):
return p.weight/(p.height**2)

p=People('EGON',75,1.81)
print(p.bmi)

为什么要用property

将一个类的函数定义成特性以后,对象再去使用的时候obj.name,

根本无法察觉自己的name是执行了一个函数然后计算出来的,

这种特性的使用方式遵循了统一访问的原则

知识延伸

class Foo:
def __init__(self,val):
self.__NAME=val #将所有的数据属性都隐藏起来

@property
def name(self):
return self.__NAME #obj.name访问的是self.__NAME(这也是真实值的存放位置)

@name.setter     #修改
def name(self,value):
if not isinstance(value,str): #在设定值之前进行类型检查
raise TypeError('%s must be str' %value)
self.__NAME=value #通过类型检查后,将值value存放到真实的位置self.__NAME

@name.deleter    #删除
def name(self):
raise TypeError('Can not delete')


f=Foo('sunny')
print(Foo.__dict__)
print(f.name)
f.name='Sunny'
print(f.name)
del f.name

总结一下:property装饰的函数属性 像 数据属性一样访问,统一了访问原则!

猜你喜欢

转载自www.cnblogs.com/sunny666/p/9651036.html
今日推荐