python property
python property
在2.6版本中,添加了一种新的类成员函数的访问方式--property。
原型
class property([fget[, fset[, fdel[, doc]]]])
fget:获取属性
fset:设置属性
fdel:删除属性
doc:属性含义
用法
1.让成员函数通过属性方式调用
class C(object):
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
a = C()
print C.x.__doc__ #打印doc
print a.x #调用a.getx() a.x = 100 #调用a.setx()
print a.x try:
del a.x #调用a.delx()
print a.x #已被删除,报错
except Exception, e:
print e
输出结果:
I'm the 'x' property.
None
100
'C' object has no attribute '_x'
2.利用property装饰器,让成员函数称为只读的
class Parrot(object):
def __init__(self):
self._voltage = 100000 @property
def voltage(self):
"""Get the current voltage."""
return self._voltage a = Parrot()
print a.voltage #通过属性调用voltage函数
try:
print a.voltage() #不允许调用函数,为只读的
except Exception as e:
print e
输出结果:
100000
'int' object is not callable
3.利用property装饰器实现property函数的功能
class C(object):
def __init__(self):
self._x = None @property
def x(self):
"""I'm the 'x' property."""
return self._x @x.setter
def x(self, value):
self._x = value @x.deleter
def x(self):
del self._x
其他应用
1.bottle源码中的应用
class Request(threading.local):
""" Represents a single request using thread-local namespace. """
... @property
def method(self):
''' Returns the request method (GET,POST,PUT,DELETE,...) '''
return self._environ.get('REQUEST_METHOD', 'GET').upper() @property
def query_string(self):
''' Content of QUERY_STRING '''
return self._environ.get('QUERY_STRING', '') @property
def input_length(self):
''' Content of CONTENT_LENGTH '''
try:
return int(self._environ.get('CONTENT_LENGTH', ''))
except ValueError:
return 0 @property
def COOKIES(self):
"""Returns a dict with COOKIES."""
if self._COOKIES is None:
raw_dict = Cookie.SimpleCookie(self._environ.get('HTTP_COOKIE',''))
self._COOKIES = {}
for cookie in raw_dict.values():
self._COOKIES[cookie.key] = cookie.value
return self._COOKIES
2.在django model中的应用,实现连表查询
from django.db import models class Person(models.Model):
name = models.CharField(max_length=30)
tel = models.CharField(max_length=30) class Score(models.Model):
pid = models.IntegerField()
score = models.IntegerField() def get_person_name():
return Person.objects.get(id=pid) name = property(get_person_name) #name称为Score表的属性,通过与Person表联合查询获取name
python property的更多相关文章
- python property详解
Python中有一个被称为属性函数(property)的小概念,它可以做一些有用的事情.在这篇文章中,我们将看到如何能做以下几点: 将类方法转换为只读属性 重新实现一个属性的setter和getter ...
- python property装饰器
直接上代码: #!/usr/bin/python #encoding=utf-8 """ @property 可以将python定义的函数“当做”属性访问,从而提供更加友 ...
- Python @property 详解
本文讲解了 Python 的 property 特性,即一种符合 Python 哲学地设置 getter 和 setter 的方式. Python 有一个概念叫做 property,它能让你在 Pyt ...
- Python property() 函数
Python property() 函数 Python 内置函数 描述 property() 函数的作用是在新式类中返回属性值. 语法 以下是 property() 方法的语法: class pro ...
- python property用法
参考 http://openhome.cc/Gossip/Python/Property.html http://pyiner.com/2014/03/09/Python-property.html ...
- python - property 属性函数
Python中有一个被称为属性函数(property)的小概念,它可以做一些有用的事情.在这篇文章中,我们将看到如何能做以下几点: 将类方法转换为只读属性 重新实现一个属性的setter和getter ...
- Python中“*”和“**”的用法 || yield的用法 || ‘$in’和'$nin' || python @property的含义
一.单星号 * 采用 * 可将列表或元祖中的元素直接取出,作为随机数的上下限: import random a = [1,4] print(random.randrange(*a)) 或者for循环输 ...
- python property理解
一般情况下我这样使用property: @property def foo(self): return self._foo # 下面的两个decrator由@property创建 @foo.sette ...
- [转载]python property
@property 简单解释. http://python.jobbole.com/80955/
随机推荐
- 解析jquery获取父窗口的元素
("#父窗口元素ID",window.parent.document); 对应javascript版本为window.parent.document.getElementByIdx ...
- react-router配合webpack实现按需加载
很久没有写博客了.一直感觉没有什么要写的,但是这个东西确实有必要的.使用react开发,不可能一直打包到一个文件.小项目肯定没有问题,但是变大一旦到几兆,这个问题就很严重.现在又Commonjs,AM ...
- PS:缝线颜色随着鞋帮颜色的改变发生改变.files
1.绘制逼真缝线 (1)新建两个图层,并且命名为“针眼”和“缝线”: (2)选择“铅笔”工具,像素为“2”: (3)在针孔图层上进行缝线路径描边,并双击图层,弹出“图层样式”窗口,选择“斜面与浮雕”- ...
- Jpanel和container和jframe的区别
Jpanel和container和jframe的区别 (2012-05-23 19:15:11) 转载▼ 标签: 杂谈 分类: room 看到上上面的几张图,container容器是位于最高层. 下面 ...
- 删除所选项(附加搜索部分的jquery)
1.视图端(views)的配置为: <script> $(document).ready(function() { $("#info-grid").kendoGrid( ...
- html之间的传值
传值:window.location.href=“eidit.html?activityId=“+acytivityIDd: 将id放进地址栏传到另一html页面 接受 再用var str=wind ...
- CAD二次开发---导入外部文件中的块并输出预览图形(五)
思路: 1)首先要定义一个数据库对象来表示包含块的文件,改数据库对象会被加载到内存中,但不会被显示在CAD窗口中. 2)调用Database类的ReadDwgFile函数将外部文件DWG文件读入到新创 ...
- SharePoint 2013异常信息的查看
刚刚学习SharePoint开发的时候,经常遇到一些异常,却不能直接看到详细信息,很郁闷.这里做下简单的整理,方便查找: 1.代码未处理异常出现黄页——”‘/’应用程序中的服务器错误.运行时错误“. ...
- NOIP2014 总结
想了很久,才开始动笔. 怎么说,感觉挺对不起自己的.愚蠢的失误让我正好卡着一等线,真希望不要是二等奖. 最难过的是,努力全葬送在愚蠢上面了. 不过也好,学会平静自己也是一种能力. 半期考试也遭的一塌糊 ...
- Samba网络配置
Samba网络配置 操作环境 ubuntu14.04 1. 更新Linux源列表 sudo apt-get update 2. 安装Samba服务 sudo apt-get install samba ...