python中Properties的一些小用法
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的一些小用法的更多相关文章
- 简单说明Python中的装饰器的用法
简单说明Python中的装饰器的用法 这篇文章主要简单说明了Python中的装饰器的用法,装饰器在Python的进阶学习中非常重要,示例代码基于Python2.x,需要的朋友可以参考下 装饰器对与 ...
- Python中【__all__】的用法
Python中[__all__]的用法 转:http://python-china.org/t/725 用 __all__ 暴露接口 Python 可以在模块级别暴露接口: __all__ = [&q ...
- python中enumerate()函数用法
python中enumerate()函数用法 先出一个题目:1.有一 list= [1, 2, 3, 4, 5, 6] 请打印输出:0, 1 1, 2 2, 3 3, 4 4, 5 5, 6 打印输 ...
- Python中try...except...else的用法
Python中try...except...else的用法: try: <语句>except <name>: <语句> #如果在try ...
- Python中logging模块的基本用法
在 PyCon 2018 上,Mario Corchero 介绍了在开发过程中如何更方便轻松地记录日志的流程. 整个演讲的内容包括: 为什么日志记录非常重要 日志记录的流程是怎样的 怎样来进行日志记录 ...
- (转)Python中的split()函数的用法
Python中的split()函数的用法 原文:https://www.cnblogs.com/hjhsysu/p/5700347.html Python中有split()和os.path.split ...
- Python中zip()与zip(*)的用法
目录 Python中zip()与zip(*)的用法 zip() 知识点来自leetcode最长公共前缀 Python中zip()与zip(*)的用法 可以看成是zip()为压缩,zip(*)是解压 z ...
- python中的随机函数random的用法示例
python中的随机函数random的用法示例 一.random模块简介 Python标准库中的random函数,可以生成随机浮点数.整数.字符串,甚至帮助你随机选择列表序列中的一个元素,打乱一组数据 ...
- 详解Python中的循环语句的用法
一.简介 Python的条件和循环语句,决定了程序的控制流程,体现结构的多样性.须重要理解,if.while.for以及与它们相搭配的 else. elif.break.continue和pass语句 ...
随机推荐
- 【原】eclipse创建maven工程时,如何修改默认JDK版本?
问题描述:eclipse建立maven项目时,JDK版本默认是1.5,想创建时默认版本设置为1.8,如何修改? 解决方案: 找到本机maven仓库存放位置,比如:${user.home}/.m2/路径 ...
- Python Cookbook(第3版)中文版:15.17 传递文件名给C扩展
15.17 传递文件名给C扩展¶ 问题¶ 你需要向C库函数传递文件名,但是需要确保文件名根据系统期望的文件名编码方式编码过. 解决方案¶ 写一个接受一个文件名为参数的扩展函数,如下这样: static ...
- 关系型数据库工作原理-事务管理(二)(翻译自Coding-Geek文章)
本文翻译自Coding-Geek文章:< How does a relational database work>. 原文链接:http://coding-geek.com/how-dat ...
- oracle使用中的一些问题
一.设置自增主键(假设表的主键名为:company_id) 1)创建序列(company_autoinc): maxvalue start increment nocache; 2)创建触发器(com ...
- wpf研究之道-grid控件
想要说些什么,却不知道从哪开始."形而上谓之道,形而下谓之器".与其坐而论道,不如脚踏实地,从最实用的地方开始. 我们先来看看wpf中的grid控件.grid控件是个网格的布局控件 ...
- 构造方法里的super()方法
为什么经常会遇到有的构造函数会有super(),而有的却没有,其实super就比如 对数函数,log的底数为10,如果为10 ,我们可写可不写,如果不为10,那么我们就要加上底数 在子类构造方法中,s ...
- php文件上传原理详解(含源码)
1.文件上传原理 将客户端的文件上传到服务器,再将服务器的临时文件上传到指定目录 2.客户端配置 提交表单 表单的发送方式为post 添加enctype="multipart/form-da ...
- oc 与 js交互之vue.js
- .vue.js 调用oc的方法并传值 vue.js 组件中调用方法: methods: { gotoDetail(item){ //此方法需要在移动端实现,这里可以加入判断 ...
- 关于browser-sync(在多个设备上进行网页调试)的问题点总结
最近在看响应式网站的开发视频,其中有一部分非常有用,就是在多个设备上进行网页调试,通过使用browser-sync来实现,具体的步骤可以参照官网(http://www.browsersync.cn/) ...
- prompt 方法显示输入对话框
prompt 方法显示输入对话框 原理: prompt() 方法用于与用户交互,提示用户输入信息的对话框. prompt(str1,str2);此方法包含两个属性: str1:用于提示用户输入的信息. ...