静态属性property(是通过对象去使用)
property是一种特殊的属性,访问它时会执行一段功能(函数)然后返回值
1 . 通过@property修饰过的函数属性,调用的时候无需在加()
class Foo:
@property
def f1(self):
print("f1")
f = Foo()
f.f1
输出:
f1
1.BMI指数案例
成人的BMI数值:
过轻:低于18.5
正常:18.5-23.9
过重:24-27
肥胖:28-32
非常肥胖, 高于32
体质指数(BMI)=体重(kg)÷身高^2(m)
EX:70kg÷(1.75×1.75)=22.86
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)
p = People("zhangsan",75,1.78)
print(p.bmi)
输出:
23.671253629592222
2.通过唯一内部封装的方法对值进行修改@name.setter
class Foo:
def __init__(self,x):
self.__Nane = x
@property
def name(self):
return self.__Nane
@name.setter # 前提 name 这个函数已经被 property 修饰过一次;才能name.setter
def name(self,val):
if not isinstance(val,str):
raise TypeError # 触发一个错误 让程序终止
self.__Nane = val
f = Foo("lisi")
print(f.name)
f.name = "zhangsan"
print(f.name)
输出:
lisi
zhangsan