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', '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
复制代码

 

知识共享许可协议
本文 由 cococo点点 创作,采用 知识共享 署名-非商业性使用-相同方式共享 3.0 中国大陆 许可协议进行许可。欢迎转载,请注明出处:
转载自:cococo点点 http://www.cnblogs.com/coder2012


相关文章
|
5月前
|
Python
97 python高级 - 属性property
97 python高级 - 属性property
28 0
|
8月前
|
数据库 Python
【从零学习python 】61.Python中的property属性详解和应用示例
【从零学习python 】61.Python中的property属性详解和应用示例
52 0
|
11月前
|
Java 程序员 Python
一文轻松搞定Python装饰器@property
一文轻松搞定Python装饰器@property
90 0
|
数据安全/隐私保护 Python
Python property使用简介
Python property使用简介
89 0
Python装饰器3-funtools.wraps与property装饰器
funtools.wraps装饰器、property装饰器、多装饰器的执行顺序
Python装饰器3-funtools.wraps与property装饰器
|
程序员 数据库 开发者
Python中property的使用技巧
既要保护类的封装特性,又要让开发者可以使用 **对象.属性** 的方式操作方法,`@property 装饰器`,可以直接通过方法名来访问方法,不需要在方法名后添加一对 `()` 小括号。
|
Java PHP 数据库
【Python编程技巧】简单理解和使用Python中@property
如果你还学习过其他诸如java,php等面向对象编程语言的话,你会发现,其实Python面向对象跟其他的编程语言的面向对象基本是一样的,只是语言语法上的有些许的差别而已.Python中的类同样包括类的属性和类的方法.同时一样也拥有面向对象的三大特征.接下来,我们先来看看本文的主角:Python中有关于属性的概念
176 0
|
Python
【Python面向对象进阶】——@property装饰器的用法
在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把属性值随便改.
111 0
【Python面向对象进阶】——@property装饰器的用法
|
Python
Python的@property是干嘛的?| Python 主题月
Python的@property是干嘛的?| Python 主题月
|
Python
Python高级语法4:类对象和实例对象访问属性的区别和property属性
Python高级语法4:类对象和实例对象访问属性的区别和property属性
126 0