例一:BMI指数(bmi是计算而来的,但很明显它听起来像是一个属性而非方法,如果我们将其做成一个属性,更便于理解)
成人的BMI数值:
体质指数(BMI)= 体重(kg)÷ 身高^2(m)
class People:
def __init__(self, name, weight, height):
self.name = name
self.weight = weight
self.height = height
def bmi(self):
return self.weight / (self.height**2)
peo1 = People('nick', 70, 1.8)
print(peo1.bmi())
21.604938271604937
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)
peo1 = People('nick', 70, 1.8)
print(peo1.bmi)
21.604938271604937
peo1.height = 1.85
print(peo1.bmi)
20.45288531775018
class People:
def __init__(self, name):
self.__name = name
@property # 查看obj.name
def name(self):
return '<名字是:%s>' % self.__name
peo1 = People('nick')
print(peo1.name)
<名字是:nick>
try:
peo1.name = 'EGON'
except Exception as e:
print(e)
can't set attribute
class People:
def __init__(self, name):
self.__name = name
@property # 查看 obj.name
def name(self):
return '<名字是:%s>' % self.__name
@name.setter # 修改 obj.name=值 触发
def name(self, name):
if type(name) is not str:
raise TypeError('名字必须是str类型傻叉')
self.__name = name
@name.deleter # 删除 del obj.name 触发
def name(self):
# raise PermissionError('不让删')
print('不让删除傻叉')
# del self.__name
peo1 = People('nick')
print(peo1.name)
<名字是:nick>
try:
peo1.name = 10
except Exception as e:
print(e)
名字必须是str类型傻叉
peo1.name = 'Nick'
print(peo1.name)
<名字是:Nick>
del peo1.name
不让删除傻叉
class People:
def __init__(self, name):
self.__name = name
def tell_name(self):
return '<名字是:%s>' % self.__name
def set_name(self, name):
if type(name) is not str:
raise TypeError('名字必须是str类型傻叉')
self.__name = name
def del_name(self):
print('不让删除傻叉')
# 相当于添加了property、setter、deleter装饰器(推荐使用装饰器)
# 与property()方法内的函数名字无关,三个函数必须依次为打印、修改、删除
name = property(tell_name, set_name, del_name)
peo1 = People('egon')
print(peo1.name)
<名字是:egon>
peo1.name = 'EGON'
print(peo1.name)
<名字是:EGON>
del peo1.name
不让删除傻叉
import math
class Circle:
def __init__(self, radius): # 圆的半径radius
self.radius = radius
@property
def area(self):
return math.pi * self.radius**2 # 计算面积
@property
def perimeter(self):
return 2 * math.pi * self.radius # 计算周长
c = Circle(10)
print(c.radius)
10
print(c.area) # 可以向访问数据属性一样去访问area,会触发一个函数的执行,动态计算出一个值
314.1592653589793
print(c.perimeter) # 同上
62.83185307179586
原文:https://www.cnblogs.com/nickchen121/p/10990412.html