Python propetry装饰器
作者:互联网
propetry装饰器:
把类的方法装饰成属性的工具
class Student():
def __init__(self,name,age,gender):
self.__name = name # 可以是普通属性,也可以是隐藏属性,
self.age = age
self.gender = gender
@propetry # 把方法装饰成属性,直接把函数名,写成属性名
def name(self):
return self.name
@name.set
def name(self,newname): # 调用上面装饰后的方法名
if not isinstance(newname,str):
print('数据类型错误')
return
self.name = newname
调用:
stu = Student('ly',18,'male')
stu.name # 查看name
stu.name = 'newname' # 修改name
例:
class Bmi():
def __init__(self, height, weight):
self.height = height
self.weight = weight
@property
def get_bmi(self):
return self.weight / (self.height ** 2)
bmi = Bmi(1.8, 70)
print(bmi.get_bmi)
标签:__,name,weight,Python,self,newname,装饰,def,propetry 来源: https://www.cnblogs.com/qiubuyu/p/15645552.html