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

    def __init__(self, fget=None, fset=None, fdel=None, doc=None): # known special case of property.__init__
"""
property(fget=None, fset=None, fdel=None, doc=None) -> property attribute fget is a function to be used for getting an attribute value, and likewise
fset is a function for setting, and fdel a function for del'ing, an
attribute. Typical use is to define a managed attribute x: class C(object):
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.") Decorators make defining new properties or modifying existing ones easy: class C(object):
@property
def x(self):
"I am the 'x' property."
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x # (copied from class doc)
"""
pass

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

class Rectangle(object):
def __init__(self, x1, y1, x2, y2):
self.x1, self.y1 = x1, y1
self.x2, self.y2 = x2, y2 def _width_get(self):
return self.x2 - self.x1 def _width_set(self, value):
self.x2 = self.x1 + value def _height_get(self):
return self.y2 - self.y1 def _height_set(self, value):
self.y2 = self.y1 + value width = property(_width_get, _width_set, doc="rectangle width measured from left")
height = property(_height_get, _height_set, doc="rectangle height measured from top") def __repr__(self):
return "{}({}, {}, {}, {})".format(self.__class__.__name__,
self.x1,
self.y1,
self.x2,
self.y2) rectangle = Rectangle(10, 10, 30, 15)
print(rectangle.width, rectangle.height)
rectangle.width = 50
print(rectangle)
rectangle.height = 50
print(rectangle)
print(help(rectangle))

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

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

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

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

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

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

class Rectangle(object):
def __init__(self, x1, y1, x2, y2):
self.x1, self.y1 = x1, y1
self.x2, self.y2 = x2, y2 @property
def width(self):
"""rectangle width measured from left"""
return self.x2 - self.x1 @width.setter
def width(self, value):
self.x2 = self.x1 + value @property
def height(self):
return self.y2 - self.y1 @height.setter
def height(self, value):
self.y2 = self.y1 + value def __repr__(self):
return "{}({}, {}, {}, {})".format(self.__class__.__name__,
self.x1,
self.y1,
self.x2,
self.y2) rectangle = Rectangle(10, 10, 30, 15)
print(rectangle.width, rectangle.height)
rectangle.width = 50
print(rectangle)
rectangle.height = 50
print(rectangle)
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. AVStream ddk 翻译

    1.       AVStream概览 AVStream是一款微软提供的多媒体类驱动程序,它既支持单独的视频流媒体,也支持音频视频集成的流媒体.微软把AVStream作为操作系统的一部分,在驱动程序k ...

  2. unix时间戳转换成标准时间(c#)

    //---unix时间戳转换成标准时间(c#)---//     /*     string timeStamp = "1144821796";     DateTime dtSt ...

  3. mybatis的动态增删改查

    1.动态SQL片段 通过SQL片段达到代码复用 <!-- 动态条件分页查询 --> <sql id="sql_count"> select count(*) ...

  4. 如何解决 touchstart 事件与 click 事件的冲突

    一 · 业务场景的描述 在对已完成的PC站点进行移动端适配时,我们想要站点在移动设备上有更快的响应速度,以带给用户更好的体验,此时,我们应该使用移动设备专用的事件系统,例如,使用 touchstart ...

  5. 在实训时做的项目出现的ajax json数据传送的问题

    json数据在前后端数据交互的时候非常常见,但是大部分人对json都么有系统的学习过,所以就会出现一些很简单的问题却要非很大劲去解决. 在用json传递数据的时候属性必须用双引号括住,一般如果在进行字 ...

  6. Xampp apache与mySQL开不了 解决办法

    Xampp安装后,打开Xampp control panel. 点击Apache对应的Start,开不了.原因是系统的服务占用了80端口,所以要么结束系统服务,要么修改apache端口. 个人比较喜欢 ...

  7. angular 按下回车键触发事件

    angularJs  按下回车键触发事件这个功能很简单,但是今天的却让我掉坑很久.... 由于我的页面上有两个不同方法都传$event事件,如search($event)和create($event) ...

  8. iOS学习——UITableViewCell两种重用方法的区别

    今天在开发过程中用到了UITableView,在对cell进行设置的时候,我发现对UITableViewCell的重用设置的方法有如下两种,刚开始我也不太清楚这两种之间有什么区别.直到我在使用方法二进 ...

  9. LNMP详解

    目录 Nginx配置    1 PHP解析    1 Mysql操作    3 服务安装    3 连接测试    3 数据配置    3 Blogs建立    4   LNMP 环境 Mysql:1 ...

  10. SpringtMVC中配置 <mvc:annotation-driven/> 与 <mvc:default-servlet-handler/> 源码解析

    上一篇有提到,当有.无这两个标签时,SpringtMVC 底层所采用的  HandlerMapping 以及 HandlerAdapter 是不一样的.现在就来进行源码调试,揭开 SpringtMVC ...