property属性

时间:2025-03-18 21:55:30
property属性; a.一种用起来像实例属性一样的特殊属性,可以对应于某些方法,property的本质还是方法 属性的定义和调用要注意几点: 1.定义时,在实例方法的基础上添加@property装饰器, 2.并且方法只有一个self参数 3.调用时无需括号 的好处: 将一个属性的操作通过property封装起来,区别于实例方法,但其本质也是方法, 调用者用起来就跟操作普通属性一样,十分简洁 有两种方式来定义property属性: 1.使用装饰器的方式定义property属性: -@property:取得属性值,修饰的方法有且只有一个self参数; -@方法名.setter:设置属性值,修饰的方法,只能传一个参数 -@方法名.deleter:删除属性的方法有且只有一个self参数 注意:这种方式用起来很简洁,但要注意其中的调用原理,他是通过类对象调用 来取得属性值,然后传递给setter设置属性值,在这部分你还可以做一些身份验证 确保数据安全,删除很少使用这种方法 2.通过类属性方式定义property属性 property()这个方法里有四个参数:def __init__(self, fget=None, fset=None, fdel=None, doc=None) 第一个参数是方法名:获取属性值 第二个参数是方法名;设置属性值 第三个参数是方法名;删除属性值 第四个参数是字符串;描述该属性的信息,通过类名.属性名.__doc__调用 参考代码: class foo(): def __init__(self): = "男男女女" self.__price = 2000 def get_price(self): print("私有财产为:%d"%self.__price) @property def prop(self): print("私有财产为:%d" % self.__price) f = foo() #1.使用实例属性访问私有属性 # print(f.__price)#无法访问 #2.通过实例方法来访问私有属性,这是传统的方式 f.get_price() #3.使用property访问私有属性 """1.使用装饰器的方式定义property属性:""" class foo(): def __init__(self): self.__price = 2000 """-@property:取得属性值,修饰的方法有且只有一个self参数; -@方法名.setter:设置属性值,修饰的方法,只能传一个参数 -@方法名.deleter:删除属性的方法有且只有一个self参数""" @property#取到属性值 def price(self): print("@property:取到属性值") return self.__price @#修改或者设置属性值 def price(self,value): print("@:设置属性值") try: self.__price=int(value) except: print("修改不成功") @#删除属性值 def price(self): print("@; 删除属性值") # del self.__price def get_price(self): print(self.__price) f = foo() print() ="5555" print() del print() """2.通过类属性方式定义property属性""" class foo(): def __init__(self): self.__price = 5000 def get_price(self): print("取到属性值") return self.__price def set_price(self,value): print("修改属性名") try: self.__price=int(value) except: print("修改错误") def del_price(self): print("删除属性值") price = property(get_price,set_price,del_price,'使用类属性定义property') f = foo() print() =2550 print() print(.__doc__)