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. jsp jsp指令

    JSP 由HTML和java语句拼接而成的文本,后缀名为.jsp 1.Jsp翻译成servlet:先翻译,Tomcat将翻译后的文件放置在安装目录下(所有JSP页面本质上就是Servlet程序) 2. ...

  2. vSphere6提示已弃用VMFS卷的解决方法

    Deprecated VMFS volume(s) found on the host. Please consider upgrading volume(s) to the latest versi ...

  3. 华硕U303L通过U盘装系统

    开机,按esc,进入bios,选择security,将secure boot control设置为disable.   在boot下,将launch csm 改为enable,按F10保存退出,重启. ...

  4. android检测版本更新

    原理就是从服务器获取版本号和本得apk的版本号对比更新: //检查更新        Activity activity = this;        while(activity.getParent ...

  5. CSS有三种基本的定位机制

    CSS有三种基本的定位机制:普通流,浮动和绝对定位. 普通流:在普通流中元素框的位置由元素在html中的位置决定, 1.元素position属性为static或继承来的static时就会按照普通流定位 ...

  6. mysql text字段判断是否为空

    mysql text字段判断是否为空 mysql text字段为空select * from `tableName` where `textField` is null or `textField` ...

  7. php代码优化系列 -- array_walk 和 foreach, for 的效率的比较

    实验是我学习计算机科学的一个重要方法,计算机科学不是简单的智力游戏,它本质上来说不是一门科学,而是一个改造世界的工具.数学方法和实验方法是计算机研究的基本方法,也是我们学习的基本方法,数学锻炼我们的思 ...

  8. Spring JdbcTemplate 调用存储过程

    遇到调用存储过程的业务,以前有用过,但不是用Spring的 JdbcTemplate去做的,这次是在一个已经有的SpringMVC框架的项目下写处理存储过程的. 参考网络中的方法,在实际操作中遇到两个 ...

  9. oracle的加密和解密

    加密函数 create or replace function encrypt_des(p_text varchar2, p_key varchar2) return varchar2 isv_tex ...

  10. Oracle学习笔记2

    主键 create table userinfo_test( userid number(3,0), username varchar2(20), pwd varchar2(20), constrai ...