Python中的property() 函数 和@property 装饰符
来源:互联网 发布:淘宝js 编辑:程序博客网 时间:2024/05/22 06:52
http://www.linuxidc.com/Linux/2011-10/45082.htm
大家也许知道C#中提供了属性Property这个概念,让我们在对私有成员赋值、获取时更加方便,而不用像C++分别定义set*和get*两个函数,在使用时也就像直接使用变量一样。
今天突然发现Python中竟然也提供了如此类似的方法,感到甚为亲切,发上来大家一起讨论一下,有不妥的地方还请多多指教。
假设定义了一个类:C,该类必须继承自object类,有一私有变量__x
- class C:
- def __init__(self):
- self.__x=None
- 1.现在介绍第一种使用属性的方法:
- 在该类中定义三个函数,分别用作赋值、取值和删除变量(此处表达也许不很清晰,请看示例)
- def getx(self):
- return self.__x
- def setx(self,value):
- self.__x=value
- def delx(self):
- del self.__x
现在这个类中的x属性便已经定义好了,我们可以先定义一个C的实例c=C(),然后赋值c.x=100,取值y=c.x,删除:del c.x。是不是很简单呢?请看第二种方法
下面看第二种方法(在2.6中新增)
首先定义一个类C:
- class C:
- def __init__(self):
- self.__x=None
- 下面就开始定义属性了
- @property
- def x(self):
- return self.__x
- @x.setter
- def x(self,value):
- self.__x=value
- @x.deleter
- def x(self):
- del self.__x
2 0
- Python中的property() 函数 和@property 装饰符
- Python中的property() 函数 和@property 装饰符
- Python中的@property和property函数
- python中的@property装饰器
- python中的property函数
- python中的property函数
- Python中的property, setter装饰器
- Python @property装饰器
- python装饰器--@property
- 函数装饰@property等
- Python装饰器之 property()
- Python----@property 可以用装饰器函数 get/set方法
- python描述符和property
- @property 装饰
- python @classmethod和@staticmethod、@property以及装饰器
- python描述符(descriptor)、属性(property)、函数(类)装饰器(decorator )原理实例详解
- [Python]属性和property内建函数
- python 的property函数
- eclipse初始化设置
- android Universal-Image-Loader的简单使用
- 清爽明亮收纳窝 90平小户型显大气
- ajax获取不到Ueditor值的问题
- hdu2296 AC自动机+DP
- Python中的property() 函数 和@property 装饰符
- Ganglia监控Hadoop集群的安装部署
- Week10---5月7日
- javascript中闭包学习笔记
- OC_ 分类和协议
- Python 之 @property
- 设计模式(结构型)之代理模式(Proxy Pattern)
- Android lint发现隐藏的Bug
- Php操作redis写入对象和查询对象