property最大的用处就是可以为一个属性制定getter,setter,delete和doc,他的函数原型为:

  1. def __init__(self, fget=None, fset=None, fdel=None, doc=None): # known special case of property.__init__
  2. """
  3. property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
  4. fget is a function to be used for getting an attribute value, and likewise
  5. fset is a function for setting, and fdel a function for del'ing, an
  6. attribute. Typical use is to define a managed attribute x:
  7. class C(object):
  8. def getx(self): return self._x
  9. def setx(self, value): self._x = value
  10. def delx(self): del self._x
  11. x = property(getx, setx, delx, "I'm the 'x' property.")
  12. Decorators make defining new properties or modifying existing ones easy:
  13. class C(object):
  14. @property
  15. def x(self):
  16. "I am the 'x' property."
  17. return self._x
  18. @x.setter
  19. def x(self, value):
  20. self._x = value
  21. @x.deleter
  22. def x(self):
  23. del self._x
  24. # (copied from class doc)
  25. """
  26. pass

从上边的代码中可以看出来,它一共接受4个参数,我们再继续看一段代码:

  1. class Rectangle(object):
  2. def __init__(self, x1, y1, x2, y2):
  3. self.x1, self.y1 = x1, y1
  4. self.x2, self.y2 = x2, y2
  5. def _width_get(self):
  6. return self.x2 - self.x1
  7. def _width_set(self, value):
  8. self.x2 = self.x1 + value
  9. def _height_get(self):
  10. return self.y2 - self.y1
  11. def _height_set(self, value):
  12. self.y2 = self.y1 + value
  13. width = property(_width_get, _width_set, doc="rectangle width measured from left")
  14. height = property(_height_get, _height_set, doc="rectangle height measured from top")
  15. def __repr__(self):
  16. return "{}({}, {}, {}, {})".format(self.__class__.__name__,
  17. self.x1,
  18. self.y1,
  19. self.x2,
  20. self.y2)
  21. rectangle = Rectangle(10, 10, 30, 15)
  22. print(rectangle.width, rectangle.height)
  23. rectangle.width = 50
  24. print(rectangle)
  25. rectangle.height = 50
  26. print(rectangle)
  27. print(help(rectangle))

通过property,我们有能力创造出一个属性来,然后为这个属性指定一些方法,在这里用setter,getter的好处就是可以监听属性的赋值和获取行为,表面上看上去上边的代码没有问题,但是当出现继承关系的时候,就出问题了。

  1. class MetricRectangle(Rectangle):
  2. def _width_get(self):
  3. return "{} metric".format(self.x2 - self.x1)
  4. mr = MetricRectangle(10, 10, 100, 100)
  5. print(mr.width)

即使我们在子类中重写了getter方法,结果却是无效的,这说明property只对当前的类生效,于是不得不把代码改成下边这样:

  1. class MetricRectangle(Rectangle):
  2. def _width_get(self):
  3. return "{} metric".format(self.x2 - self.x1)
  4. width = property(_width_get, Rectangle.width.fset)
  5. mr = MetricRectangle(10, 10, 100, 100)
  6. print(mr.width)

因此,在平时的编程中,如果需要重写属性的话,应该重写该类中所有的property,否则程序很很难以理解,试想一下,setter在子类,getter在父类,多么恐怖

另一种比较好的方案是使用装饰器,可读性也比较好

  1. class Rectangle(object):
  2. def __init__(self, x1, y1, x2, y2):
  3. self.x1, self.y1 = x1, y1
  4. self.x2, self.y2 = x2, y2
  5. @property
  6. def width(self):
  7. """rectangle width measured from left"""
  8. return self.x2 - self.x1
  9. @width.setter
  10. def width(self, value):
  11. self.x2 = self.x1 + value
  12. @property
  13. def height(self):
  14. return self.y2 - self.y1
  15. @height.setter
  16. def height(self, value):
  17. self.y2 = self.y1 + value
  18. def __repr__(self):
  19. return "{}({}, {}, {}, {})".format(self.__class__.__name__,
  20. self.x1,
  21. self.y1,
  22. self.x2,
  23. self.y2)
  24. rectangle = Rectangle(10, 10, 30, 15)
  25. print(rectangle.width, rectangle.height)
  26. rectangle.width = 50
  27. print(rectangle)
  28. rectangle.height = 50
  29. print(rectangle)
  30. print(help(rectangle))

python中Properties的一些小用法的更多相关文章

  1. 简单说明Python中的装饰器的用法

    简单说明Python中的装饰器的用法 这篇文章主要简单说明了Python中的装饰器的用法,装饰器在Python的进阶学习中非常重要,示例代码基于Python2.x,需要的朋友可以参考下   装饰器对与 ...

  2. Python中【__all__】的用法

    Python中[__all__]的用法 转:http://python-china.org/t/725 用 __all__ 暴露接口 Python 可以在模块级别暴露接口: __all__ = [&q ...

  3. python中enumerate()函数用法

    python中enumerate()函数用法 先出一个题目:1.有一 list= [1, 2, 3, 4, 5, 6]  请打印输出:0, 1 1, 2 2, 3 3, 4 4, 5 5, 6 打印输 ...

  4. Python中try...except...else的用法

    Python中try...except...else的用法: try:    <语句>except <name>:    <语句>          #如果在try ...

  5. Python中logging模块的基本用法

    在 PyCon 2018 上,Mario Corchero 介绍了在开发过程中如何更方便轻松地记录日志的流程. 整个演讲的内容包括: 为什么日志记录非常重要 日志记录的流程是怎样的 怎样来进行日志记录 ...

  6. (转)Python中的split()函数的用法

    Python中的split()函数的用法 原文:https://www.cnblogs.com/hjhsysu/p/5700347.html Python中有split()和os.path.split ...

  7. Python中zip()与zip(*)的用法

    目录 Python中zip()与zip(*)的用法 zip() 知识点来自leetcode最长公共前缀 Python中zip()与zip(*)的用法 可以看成是zip()为压缩,zip(*)是解压 z ...

  8. python中的随机函数random的用法示例

    python中的随机函数random的用法示例 一.random模块简介 Python标准库中的random函数,可以生成随机浮点数.整数.字符串,甚至帮助你随机选择列表序列中的一个元素,打乱一组数据 ...

  9. 详解Python中的循环语句的用法

    一.简介 Python的条件和循环语句,决定了程序的控制流程,体现结构的多样性.须重要理解,if.while.for以及与它们相搭配的 else. elif.break.continue和pass语句 ...

随机推荐

  1. JSON对象转换成JSON字符串

    1.问题背景 有一个json对象,需要将其转换成json字符串 JSON.stringify(obj) 2.实现源码 <!DOCTYPE html PUBLIC "-//W3C//DT ...

  2. Docker 入门之swarm部署web应用

    笔者近期在利用的docker搭建一个swarm集群,目前的应用还是入门级的,读者可自行根据自己的需要修改自己需要部署的应用,今天笔者介绍的是一个web应用的swarm集群的搭建.看这篇文章之前,我希望 ...

  3. Linux之磁盘与文件系统管理

    磁盘及文件系统管理详解 [参考文献:马哥视频] 原文:http://blog.csdn.net/u013008795/article/details/51150075 目前市场上主流的磁盘是机械式硬盘 ...

  4. sql数据库设置自定义消息

    第一步 EXEC sp_addmessage   @msgnum =   50005 ,   @severity =   10 ,   @msgtext =   '更新失败'        ,  @l ...

  5. 在ASP.NET 中检测手机浏览器(转)

    引言 之前做的项目中需要在浏览器查看PDF文件.在电脑端没有问题,但是手机端网页打开失败. 后来使用了pdf.js,个人认为pdf.js的页面不够清爽,就希望网站能自动检测登录设备,电脑端保持原样,手 ...

  6. 第二篇:数据可视化 - 基本API

    前言 数据可视化是数据挖掘非常重要的一个环节,它不单在查阅了解数据环节使用到,在整个数据挖掘的流程中都会使用到. 因为数据可视化不单可以形象地展示数据,让你对数据有更好的总体上的了解,而且还可以让你清 ...

  7. 【BZOJ2428】均分数据(模拟退火)

    [BZOJ2428]均分数据(模拟退火) 题面 BZOJ 题解 先说说黄学长的做法: 当温度比较高的时候,贪心 每次随机一个数,把他放进当前和最少的那一组里面 温度足够低的时候就完全随机然后转移 这样 ...

  8. Luogu1121:环状最大两段子段和

    题面 传送门 Sol 两种情况 第一种就是类似\(***000***000***(0表示选)\),这个可以DP 设\(h[0/1/2/3][i]\)表示到第\(i\)位的状态: \(0\):表示还没选 ...

  9. [BZOJ2467] [中山市选2010] 生成树 (排列组合)

    Description 有一种图形叫做五角形圈.一个五角形圈的中心有1个由n个顶点和n条边组成的圈.在中心的这个n边圈的每一条边同时也是某一个五角形的一条边,一共有n个不同的五角形.这些五角形只在五角 ...

  10. 软件测试必备-前端知识点之css基础及ps的用法

    CSS 一. css定义 css样式表.层叠样式表,级联样式表 二. css基础语法 1. 写style标签,放在head标签里面的最后位置 2. 自己写的css代码,放在style标签里面 三. c ...