property
property是一种特殊的属性,访问它时会执行一段功能(函数)然后返回值;就是把一个函数属性的访问方式变成像访问数据属性的方式一样。
我们首先来看一个对比效果
例一:在调用 bmi 函数的时候需要加括号的,可是我们往往需要另一种调用方法——不想加括号
class people(): def __init__(self, name, height, weight): self.name = name self.height = height self.weight = weight def bmi(self): return self.weight / (self.height ** 2) p = people('ysg', 1.8, 75) print(p.bmi()) # 结果:23.148148148148145
例二:使用 property 后,则调用不需要在使用括号了
class people(): def __init__(self, name, height, weight): self.name = name self.height = height self.weight = weight @property def bmi(self): return self.weight / (self.height ** 2) p = people('ysg', 1.8, 75) print(p.bmi) # 结果:23.148148148148145 # 使用加括号调用的会报错:TypeError: 'float' object is not callable
property 的其他用法,并不常用 前提条件