property 装饰器的作用

property 装饰器将方法包装成属性,将私有属性公有化,此属性只能被读取。相当于实现get方法的对象

class People:
def __init__(self, identity_number):
self._identity_number = identity_number @property # 只读
def age(self):
return self._age @age.setter # 写
def age(self, value):
if not isinstance(value, int):
raise ValueError("age must be an integer!")
if value < 0:
raise ValueError("age must more than 0")
self._age = value @age.deleter # 删除
def age(self):
del self._age @property
def get_identity_number(self):
return self._identity_number #In [22]: p = People(123456) #In [23]: p.age = 18 # In [24]: p.age
# Out[24]: 18 # In [25]: del p.age # In [26]: p.age
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-26-3523b116dc0e> in <module>()
----> 1 p.age <ipython-input-21-de21f31a52ce> in age(self)
5 @property # 只读
6 def age(self):
----> 7 return self._age
8
9 @age.setter # 写 AttributeError: 'People' object has no attribute '_age' # In [27]: p.age = 18 # In [28]: p.age = 18.6
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-8a03211dcd49> in <module>()
----> 1 p.age = 18.6 <ipython-input-21-de21f31a52ce> in age(self, value)
10 def age(self, value):
11 if not isinstance(value, int):
---> 12 raise ValueError("age must be an integer!")
13 if value < 0:
14 raise ValueError("age must more than 0") ValueError: age must be an integer! # In [29]: p.age = '11'
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-29-b6d20eff2848> in <module>()
----> 1 p.age = '11' <ipython-input-21-de21f31a52ce> in age(self, value)
10 def age(self, value):
11 if not isinstance(value, int):
---> 12 raise ValueError("age must be an integer!")
13 if value < 0:
14 raise ValueError("age must more than 0") ValueError: age must be an integer! # In [30]: p.age = -1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-30-47db6d5817ed> in <module>()
----> 1 p.age = -1 <ipython-input-21-de21f31a52ce> in age(self, value)
12 raise ValueError("age must be an integer!")
13 if value < 0:
---> 14 raise ValueError("age must more than 0")
15 self._age = value
16 ValueError: age must more than 0 # In [31]:

会把成员函数x转换为getter,相当于做了x = property(); x = x.getter(x_get)

  • @property表示只读。
  • 同时有@property和@x.setter表示可读可写。
  • 同时有@property和@x.setter和@x.deleter表示可读可写可删除。

参考资料:https://docs.python.org/3/library/functions.html?highlight=property#property

http://blog.willdx.me/web/面向对象进阶.html

内置装饰器二:@property的更多相关文章

  1. python基础语法16 面向对象3 组合,封装,访问限制机制,内置装饰器property

    组合: 夺命三问: 1.什么是组合? 组合指的是一个对象中,包含另一个或多个对象. 2.为什么要用组合? 减少代码的冗余. 3.如何使用组合? 耦合度: 耦: 莲藕 ---> 藕断丝连 - 耦合 ...

  2. property内置装饰器函数和@name.setter、@name.deleter

    # property # 内置装饰器函数 只在面向对象中使用 # 装饰后效果:将类的方法伪装成属性 # 被property装饰后的方法,不能带除了self外的任何参数 from math import ...

  3. python进阶04 装饰器、描述器、常用内置装饰器

    python进阶04 装饰器.描述器.常用内置装饰器 一.装饰器 作用:能够给现有的函数增加功能 如何给一个现有的函数增加执行计数的功能 首先用类来添加新功能 def fun(): #首先我们定义一个 ...

  4. python内置装饰器

    前言 接着上一篇笔记,我们来看看内置装饰器property.staticmethod.classmethod 一.property装饰器 1. 普通方式修改属性值 code class Celsius ...

  5. classmethod、staticclassmethod内置装饰器函数

    # method 英文是方法的意思 # classmethod 类方法 # 当一个类中的方法中只涉及操作类的静态属性时,此时在逻辑上,我们想要直接通过类名就可以调用这个方法去修改类的静态属性,此时可以 ...

  6. Python内置装饰器@property

    在<Python装饰器(Decorators )>一文中介绍了python装饰器的概念,日常写代码时有一个装饰器很常见,他就是内置的@property. 我们一步步的来接近这个概念. 一个 ...

  7. 面向对象——组合、封装、访问限制机制、property内置装饰器

    面向对象--组合.封装.访问限制机制.property 组合 什么是组合? 组合指的是一个对象中,包含另一个或多个对象 为什么要组合? 减少代码的冗余 怎么用组合? # 综合实现 # 父类 class ...

  8. python之内置装饰器(property/staticmethod/classmethod)

    python内置了property.staticmethod.classmethod三个装饰器,有时候我们也会用到,这里简单说明下 1.property 作用:顾名思义把函数装饰成属性 一般我们调用类 ...

  9. Python 内置装饰器

    内置的装饰器 ​ 内置的装饰器和普通的装饰器原理是一样的,只不过返回的不是函数,而是类对象,所以更难理解一些. @property ​ 在了解这个装饰器前,你需要知道在不使用装饰器怎么写一个属性. d ...

随机推荐

  1. struts工作原理(图解)

    Struts2框架的工作原理: 1.服务器启动,会加载我们的xml配置文件中的内容. 2.服务器启动之后,过来一个servlet请求,如user类中的save方法.请求过来先过过滤器(strutsPr ...

  2. Asia Stock Exchanges[z]

    Asia Stock Exchanges July 7, 2009 This article is to summarise the trading rules of some Asia stocke ...

  3. VMware下的Linux系统中Windows的共享目录,不支持创建软连接

    [问题]  在编译VMware下的Linux系统对从Windows中共享过来的文件,进行编译的时候,遇到:  ln: creating symbolic link XXXXXX : Operation ...

  4. Vue-cli 配置开发环境让测试服务器监听所有IP

    //config/inex.js // Various Dev Server settingshost: '0.0.0.0', // can be overwritten by process.env ...

  5. 4. Configure maven in Spring Tool Suite

    First of all, you need to copy the folder named like: Choose Window->Preferences->Maven->Us ...

  6. OSGi karaf-maven-plugin

    karaf-maven-plugin 1. 配制 karaf 启动时加载 bundle 项目中需要在 karaf 中集成 cxf-dosgi-discovery-distributed 特性,所以需要 ...

  7. 设计模式-生成者模式之c#代码

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  8. java日期正则表达式精准校验

      function checkDate(obj) {       var date=obj.value;     var re = new RegExp("(([0-9]{3}[1-9]| ...

  9. 2018.07.28 uoj#169. 【UR #11】元旦老人与数列(线段树)

    传送门 线段树好题. 维护区间加,区间取最大值,维护区间最小值,历史区间最小值. 同样先考虑不用维护历史区间最小值的情况,这个可以参考这道题的解法,维护区间最小和次小值可以解决前两个操作,然后使用历史 ...

  10. C++/C头文件 .h和 .c

    在C语言家族程序中,头文件被大量使用.一般而言,每个C++/C程序通常由头文件(header files)和定义文件(definition files)组成.头文件作为一种包含功能函数.数据接口声明的 ...