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的更多相关文章

  1. python property详解

    Python中有一个被称为属性函数(property)的小概念,它可以做一些有用的事情.在这篇文章中,我们将看到如何能做以下几点: 将类方法转换为只读属性 重新实现一个属性的setter和getter ...

  2. python property装饰器

    直接上代码: #!/usr/bin/python #encoding=utf-8 """ @property 可以将python定义的函数“当做”属性访问,从而提供更加友 ...

  3. Python @property 详解

    本文讲解了 Python 的 property 特性,即一种符合 Python 哲学地设置 getter 和 setter 的方式. Python 有一个概念叫做 property,它能让你在 Pyt ...

  4. Python property() 函数

    Python property() 函数  Python 内置函数 描述 property() 函数的作用是在新式类中返回属性值. 语法 以下是 property() 方法的语法: class pro ...

  5. python property用法

    参考 http://openhome.cc/Gossip/Python/Property.html http://pyiner.com/2014/03/09/Python-property.html ...

  6. python - property 属性函数

    Python中有一个被称为属性函数(property)的小概念,它可以做一些有用的事情.在这篇文章中,我们将看到如何能做以下几点: 将类方法转换为只读属性 重新实现一个属性的setter和getter ...

  7. Python中“*”和“**”的用法 || yield的用法 || ‘$in’和'$nin' || python @property的含义

    一.单星号 * 采用 * 可将列表或元祖中的元素直接取出,作为随机数的上下限: import random a = [1,4] print(random.randrange(*a)) 或者for循环输 ...

  8. python property理解

    一般情况下我这样使用property: @property def foo(self): return self._foo # 下面的两个decrator由@property创建 @foo.sette ...

  9. [转载]python property

    @property 简单解释. http://python.jobbole.com/80955/

随机推荐

  1. exe文件放在其他位置

    set PATH=%PATH%;%UGII_ROOT_DIR%call "E:\ZY\exe\uds_rename_parts_mohao.exe"E:\ZY\exe\uds_re ...

  2. Git入门仅这篇就够了

    版权声明:本文为博主原创文章,未经博主允许不得转载. 转载请表明出处:http://www.cnblogs.com/cavalier-/p/5978937.html 前言 大家好,我是Cavalier ...

  3. Keep It Simple Stupid!

    Kelly Johnson提出了KISS原则.他是一个飞机工程师以及航空发明家,同时也是一个管理天才,他一生中主要设计了40多架飞机,获得的荣誉相当之多,总之,很牛. 这个原则是对Johnson带领的 ...

  4. Taylor定理证明

    下图,单独打开查看 当n->inf时如果 Rn(c)趋0, c属于(a,x), 那么在区间(a,x) 内函数在a点生成的taylor级数收敛到函数f.

  5. 什么是SQL注入

    一种简单的web应用架构,: 表示层(web浏览器或呈现引擎)———>逻辑层(如C#,ASP,.NET,PHP,JSP等编程语言)———>存储层(如Microsoft SQL Server ...

  6. 20151013 C# 第一篇 流程控制语句

    20151013 流程控制语句: 1.选择语句 if … else if...else 选择语句 if(布尔表达式){  语句块:} if(布尔表达式){  语句块1:}else{  语句块2:} i ...

  7. 【转】Linux中xargs的用法

    xargs大 多数 Linux 命令都会产生输出:文件列表.字符串列表等.但如果要使用其他某个命令并将前一个命令的输出作为参数该怎么办?例如,file 命令显示文件类型(可执行文件.ascii 文本等 ...

  8. vs.net2008工具栏上找不到debug/release选项

    使用vs.net多年,以前不时会用到release发布,近几年几乎不用的.近来生成时感觉有些项目使用了release选项,因为生成的dll的位置变了.于是想调整回bebug,发现vs.net2008的 ...

  9. CSS盒模型

    CSS盒模型是CSS 可视化格式化系统的基石,它是理解样式表如何工作的核心概念.盒模型用于元素定位和页面布局.元素框的最内部分是实际的内容,直接包围内容的是内边距.内边距呈现了元素的背景.内边距的边缘 ...

  10. java 基础题 很基础, 很有趣

    都是一些非常非常基础的题,是我最近参加各大IT公司笔试后靠记忆记下来的,经过整理献给与我一样参加各大IT校园招聘的同学们,纯考Java基础功底, 老手们就不用进来了,免得笑话我们这些未出校门的孩纸们, ...