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. Mac Virtual System On Windows

    Win8.1下利用虚拟机安装苹果操作系统 所需文件: 虚拟机:VMware -10.0.1,这个就是中文版的了. 虚拟机密钥生成器:vm10keygen,要对应虚拟机的版本. 虚拟机的插件: unlo ...

  2. [15]APUE:pipe / FIFO

    管道 pipe 一.概述 管道(pipe / FIFO)是一种文件,属于 pipefs 文件系统类型,可以使用 read.write.close 等系统调用进行操作 其本质是内核维护了一块缓冲区与管道 ...

  3. win7环境下安装运行gotour【转载整理】

    转载请注明出处:http://www.cnblogs.com/Vulpers/p/5562586.html 最近尝试学习golang,在某个网站(真忘了)上发现gotour是一款灰常叼的教程& ...

  4. 拦截js方法备忘录

    很明显,以下代码拦截了fusion2.dialog.invite,然后在页面执行fusion2.dialog.invite方法的时候修改了参数中的img. <script> var old ...

  5. 基本套接字编程(7) -- udp篇

    1. UDP概述         UDP 是User Datagram Protocol的简称, 中文名是用户数据报协议,是OSI(Open System Interconnection,开放式系统互 ...

  6. 斗地主——扎金花——3DMark

    public class Card {//扑克类 private String face; private String suit; // 牌面值和花色初始化 public Card(String f ...

  7. C# 部分语法总结(入门经典)

    class Program { static void Main(string[] args) { init(); System.Console.ReadKey(); } #region 接口 /// ...

  8. C#基于Office组件操作Excel

    1.    内容简介 实现C#与Excel文件的交互操作,实现以下功能: a)     DataTable 导出到 Excel文件 b)     Model数据实体导出到 Excel文件[List&l ...

  9. 8.4.2 Fresco

    Fresco是Facebook公司的黑科技:http://fresco-cn.org/ 真三级缓存,变换后的BItmap(内存),变换前的原始图片(内存),硬盘缓存.在内存管理上做到了极致.对于重度图 ...

  10. c#读取webconfig

    string Conn_str = ConfigurationManager.AppSettings["connectionString"].ToString();