[Python]属性和property内建函数
来源:互联网 发布:淘宝客申请定向计划 编辑:程序博客网 时间:2024/06/05 01:01
早期的Python版本中,我们一般用__getattr__()和__setattr__()来处理和属性相关的问题。属性的访问会涉及以上的方法(和__getattribute__()),但是如果用property()来处理这些问题,就可以写一个和属性有关的属性来处理实例属性的获取(getting)、赋值(setting)和删除(deleting)操作,就不必在使用那些特殊的方法了。
property()内建函数的四个参数,它们是:
property(fget=None, fset=None, fdel=None, doc=None)
实际上,property()是在它所在的类被创建时调用的,这些传进来的(作为参数的)方法是非绑定的,所以这些方法就是函数!
实例一:
class ProtectAndHideX(object): def __init__(self,x): assert isinstance(x,int),\ '"x" must be an integer!' self.__x = ~x def get_x(self): return ~self.__x x = property(get_x)inst = ProtectAndHideX(10)print "inst.x = ",inst.xinst.x = 20
inst.x = 10
:
AttributeError: can't set attribute
class HideX(object): def __init__(self,x): self.x = x def get_x(self): return ~self.__x def set_x(self,x): assert isinstance(x,int),\ '"x" must be an integer!' self.__x = ~x x = property(get_x, set_x) inst2 = HideX(10)print inst2.xinst2.x = 20print inst2.x10
20
实例三:
from math import pidef get_pi(dummy): return piclass PI(object): pi = property(get_pi,doc = 'Constant "pi"')inst3 = PI()print inst3.piprint PI.pi.__doc__3.14159265359
Constant "pi"
实例四:
class HideXX(object): def __init__(self, x): self.x = x @property def x(): def fget(self): return ~self.__x def fset(self,x): assert isinstance(x,int),\ '"x" must be an integer!' self.__x = ~x return locals()inst4 = HideXX(20)print inst4.xinst4.x = 40print inst4.x:
AttributeError: can't set attribute(至于为什么,还没搞明白,新式类继承自object反而不可以)
修改上述代码:
class HideXX: def __init__(self, x): self.x = x @property def x(): def fget(self): return ~self.__x def fset(self,x): assert isinstance(x,int),\ '"x" must be an integer!' self.__x = ~x return locals()inst4 = HideXX(20)print inst4.xinst4.x = 40print inst4.x20
40
实例五:
class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = valuestu = Student()stu.score = 20print stu.score
20
REF:Core Python Programming
0 0
- [Python]属性和property内建函数
- Python属性函数property
- Python中Property内建函数深入理解
- python内建函数及属性
- Python中的@property和property函数
- python 进阶之属性函数property
- Python工厂函数和内建函数
- oc构造函数和@property属性
- Python内建函数str()和repr()
- python内建函数any()和all()
- Python 内建函数和保留字
- Python中的property() 函数 和@property 装饰符
- Python中的property() 函数 和@property 装饰符
- python Property属性用法
- python Property属性用法
- python Property属性用法
- python property属性
- Python property,属性
- Android四大基本组件介绍与生命周期
- uva 10602 - Editor Nottoobad(贪心)
- linux0.11 中断和异常
- Objective-C中的作用域静态变量详解
- 用java实现终极密码游戏
- [Python]属性和property内建函数
- hdu 1141 Factstone Benchmark
- HDU 3265 Posters (线段树-扫描线)
- 从点击到呈现 — 详解一次HTTP请求(1)
- usaco3.2.2阶乘
- java 冒泡排序
- NYOJ-27 水池数目
- 那些被遗忘的按键-KEY
- OpenGL开发库的详细介绍