在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', '0'))
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(装饰器)将一个方法转换为属性,从而实现用于计算的属性.将方法转换为属性后,可以直接通过方法名来访问方法,而不需要再添加一对小括号&q ...

  2. python 属性 property、getattr()、setattr()详解

    直奔主题 使用中文注释需要使用 #-*-coding:utf-8-*- property property在python中有2中使用property方法:1.@property @属性名称.sette ...

  3. Python: 浅淡Python中的属性(property)

    起源:项目过程中需要研究youtube_dl这个开源组件,翻阅其中对类的使用,对比c#及Delphi中实现,感觉Python属性机制挺有意思.区别与高级编程语言之单一入口,在类之属性这一方面,它随意的 ...

  4. day26 python学习 对象的接口,封装,私用属性 property

    # 抽象类和接口类 #** #不崇尚接口类 #python本身支持多继承,没有接口专用的语法.但是我知道接口的概念 # 接口类:# 是规范子类的一个模板,只要接口类中定义的,就应该在子类中实现# 接口 ...

  5. python 中 property 属性的讲解及应用

    Python中property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回 property属性的有两种方式: 1. 装饰器 即:在方法上应用装饰器 2. 类属性 即 ...

  6. python的property属性

    最近看书中关于Python的property()内建函数属性内容时<python核心编程>解释的生僻难懂,但在网上看到了一篇关于property属性非常好的译文介绍. http://pyt ...

  7. 【转】python之property属性

    1. 什么是property属性 一种用起来像是使用的实例属性一样的特殊属性,可以对应于某个方法 # ############### 定义 ############### class Foo: def ...

  8. Python——私有化 和 属性property

    Python——私有化 和 属性property 一.私有化 xx: 公有变量 _x: 单前置下划线,私有化属性或方法,from somemodule import *禁止导入,类对象和子类可以访问 ...

  9. python中property属性的介绍及其应用

    Python的property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回. 使用property修饰的实例方法被调用时,可以把它当做实例属性一样 property的 ...

  10. 第7.23节 Python使用property函数定义属性简化属性访问的代码实现

    第7.23节 Python使用property函数定义属性简化属性访问的代码实现 一.    背景       在本章前面章节中,我们介绍了类相关的知识,并举例进行了说明,在这些例子中会定义一些形如 ...

随机推荐

  1. litepal的jar包

    转自http://blog.csdn.net/luohai859/article/details/39292607 LitePal是一款开源的Android数据库框架,它采用了对象关系映射(ORM)的 ...

  2. 有关WAMPSERVER 环境搭建 如何修改端口,MySQL数据库的修改

    环境搭建 http://share.weiyun.com/88896747fedd4e8b19afebea18f7684c 一.修改Apache的监听端口 1.在界面中选Apache,弹出隐藏菜单选项 ...

  3. poj3280 区间dp

    //Accepted 15880 KB 250 ms #include <cstdio> #include <cstring> #include <iostream> ...

  4. iOS 三种录制视频方式

    随着每一代 iPhone 处理能力和相机硬件配置的提高,使用它来捕获视频也变得更加有意思.它们小巧,轻便,低调,而且与专业摄像机之间的差距已经变得非常小,小到在某些情况下,iPhone 可以真正替代它 ...

  5. mysql批量写入

    MySQL批量写入语法是: INSERT INTO table (field1,field2,field3) VALUES (“a”,”b”,”c”), (“a1”,”b1”,”c1”),(“a2”, ...

  6. SVG 2D入门5 - 颜色的表示

    SVG和canvas中是一样的,都是使用标准的HTML/CSS中的颜色表示方法,这些颜色都可以用于fill和stroke属性.基本有下面这些定义颜色的方式:1. 颜色名字: 直接使用颜色名字red, ...

  7. 12-27cell 的可重用性(英雄列表应用性能的优化)

    在英雄列表中动态生成cell的代码在中, - (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N ...

  8. GPRS Sniffing Tutorial

    - Download sources into ~/gprs_sniffer git clone git://git.osmocom.org/osmocom-bb.git git clone git: ...

  9. USB peripherals can turn against their users

    Turning USB peripherals into BadUSB USB devices are connected to – and in many cases even built into ...

  10. @font-face usage

    If you haven’t been living in a cave for the past few months, you will have heard lots of talk about ...