笔记-python-语法-property

1.      property

看到@property,不明白什么意思,查找文档了解一下。

1.1.    property类

proerty是python自带的类,在

>>> property

<class 'property'>

>>> dir(property)

['__class__', '__delattr__', '__delete__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__isabstractmethod__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__set__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'deleter', 'fdel', 'fget', 'fset', 'getter', 'setter']

>>> property.__class__

<class 'type'>

官方文档:

class property(fget=None, fset=None, fdel=None, doc=None)

Return a property attribute.

fget是一个获取属性值的函数,fset是设定值的函数,fdel是删除值的函数。doc创建属性的说明文档。

案例:

class C:

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.")

运行结果如下:

>>> C.x

<property object at 0x000000BC05B078B8>

>>> dir(C)

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'delx', 'getx', 'setx', 'x']

解释:上面的代码给类C添加了一个属性x,而x是一个property对象,这样做的结果是可以像下面这样操作self._x

>>> a = C()

赋值

>>> a.x = 6

>>> a._x #6

删除

>>> del(a.x)

>>> a.x

Traceback (most recent call last):

File "<pyshell#27>", line 1, in <module>

a.x

File "E:\python\person_code\interview questions\built-in.py", line 47, in getx

return self._x

AttributeError: 'C' object has no attribute '_x'

>>> a._x

Traceback (most recent call last):

File "<pyshell#28>", line 1, in <module>

a._x

AttributeError: 'C' object has no attribute '_x'

最终的结果就是简化了实例对象属性的操作代码。

再看下面的代码:

A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function.

This is best explained with an example:

class C:

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

这里使用的装饰符实现,功能与上例没什么区别,但代码更简洁。

注意seter和deleter并不是必需的。

怎么实现的就不讨论了,总而言之它可以简化实例属性操作,简化代码。

笔记-python-语法-property的更多相关文章

  1. python 笔记2:python语法基础

    python语法学习笔记: 1 输入输出 input(),print(). name = input('input your name : ')print('hello ,'+name)print(& ...

  2. Python笔记_1语法总结

    前言导读 本章知识点是我在最初期听python视频教程的时候整理总结的笔记 对python语法的认识对以后代码的解读有着很大的帮助. 1 新建python命名规则 新建项目名 :数字编号 项目名称 新 ...

  3. python语法笔记(四)

    1.对象的属性     python一切皆对象,每个对象都可能有多个属性.python的属性有一套统一的管理方案. 属性的__dict__系统     对象的属性可能来自于其类定义,叫做类属性:还可能 ...

  4. python语法笔记(一)

    1. python中多个函数或者类定义可以放在一个.py 文件中,视为一个模块.模块的.py文件中,一般要写 if __name__ == '__mian__' 用来单独执行该模块内的某些函数. 2. ...

  5. 网络编程-Python高级语法-property属性

    知识点: 一.什么是property属性? 一种用起来像是使用的实例属性一样的特殊属性,可以对应于某个方法,Python的property属性的功能是:property属性内部进行一系列的逻辑计算,最 ...

  6. wxpython 支持python语法高亮的自定义文本框控件的代码

    在研发闲暇时间,把开发过程中比较重要的一些代码做个珍藏,下面的代码内容是关于wxpython 支持python语法高亮的自定义文本框控件的代码,应该是对大家也有用. import keywordimp ...

  7. (数据分析)第02章 Python语法基础,IPython和Jupyter Notebooks.md

    第2章 Python语法基础,IPython和Jupyter Notebooks 当我在2011年和2012年写作本书的第一版时,可用的学习Python数据分析的资源很少.这部分上是一个鸡和蛋的问题: ...

  8. 笔记-jinja2语法

    笔记-jinja2语法 1.      基本语法 控制结构 {% %} 变量取值 {{ }} 注释 {# #} 2.      变量 最常用的是变量,由Flask渲染模板时传过来,比如上例中的”nam ...

  9. 笔记-python lib-pymongo

    笔记-python lib-pymongo 1.      开始 pymongo是python版的连接库,最新版为3.7.2. 文档地址:https://pypi.org/project/pymong ...

随机推荐

  1. AngularJS 指令解析(二)

    AngularJS 指令解析(二) 第一篇我们讲过了作用域(scope)这块内容,现在我们进入正题,讲AngularJS的指令. 什么是指令? 这里我们引用官方的一句话: Custom directi ...

  2. 初学:react-native 轮播图

    参考资料:http://reactscript.com/react-native-card-carousel-component/ import React, {Component} from 're ...

  3. angularjs ng-if 慎用 备忘

    ng-if.ng-show一般情况下可以通用,二者的最明显区别就是: ng-if判断为false时,页面dom节点不会被创建,其子节点下也不会渲染,从而也就加快了dom的加载速度:ng-show则仅是 ...

  4. SPFieldLookupValue

    //得到查阅项的值SPWeb web = site.OpenWeb();SPList list = web.Lists["DemoList"];SPListItem item = ...

  5. PS:将一个图片变成圆形

    1.选择一张正方形图片并放置到PS软件中 2.选择“选框工具”->右击选择"椭圆选框工具” 3.画出你要圆形内的范围: 4.选择两种方式中的一种,实际上效果是一毛一样的 5.右下角就会 ...

  6. CToolTipCtrl使用详细解说

    很多的界面设计都需要有Tip提示,下面描述一下Tip的简单使用方法: 1. 首先要New一个CToolTipCtrl的对象m_pContentTip 2. 调用CToolTipCtrl的create函 ...

  7. 【JavaScript 封装库】BETA 1.0 测试版发布!

    /* 源码作者: 石不易(Louis Shi) 联系方式: http://www.shibuyi.net =============================================== ...

  8. Maven安装以及使用

    maven安装 1.解压maven安装包 2.右键“计算机”,选择“属性”,之后点击“高级系统设置”,点击“环境变量”,来设置环境变量. 3. 新建系统变量 MAVEN_HOME 变量值:C:\apa ...

  9. mysql [Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'information_schema.PROFILING.SEQ' which is not functionally dependent on columns in GRO

    [Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated c ...

  10. Win10远程桌面连接树莓派3时出现错误:由于安全设置

    http://blog.csdn.net/qq_33259138/article/details/52143407 在远程其树莓派时的电脑时提示错误“客户端无法建立与远程计算机的连接,远程计算机可能不 ...