如何正确地使用Python的属性和描述符
关于@property装饰器
在Python中我们使用@property装饰器来把对函数的调用伪装成对属性的访问。
那么为什么要这样做呢?因为@property让我们将自定义的代码同变量的访问/设定联系在了一起,同时为你的类保持一个简单的访问属性的接口。
举个栗子,假如我们有一个需要表示电影的类:
class Movie(object):
def __init__(self, title, description, score, ticket):
self.title = title
self.description = description
self.score = scroe
self.ticket = ticket
你开始在项目的其他地方使用这个类,但是之后你意识到:如果不小心给电影打了负分怎么办?你觉得这是错误的行为,希望Movie类可以阻止这个错误。 你首先想到的办法是将Movie类修改为这样:
class Movie(object):
def __init__(self, title, description, score, ticket):
self.title = title
self.description = description
self.ticket = ticket
if score < 0:
raise ValueError("Negative value not allowed:{}".format(score))
self.score = scroe
但这行不通。因为其他部分的代码都是直接通过Movie.score来赋值的。这个新修改的类只会在__init__方法中捕获错误的数据,但对于已经存在的类实例就无能为力了。如果有人试着运行m.scrore= -100,那么谁也没法阻止。那该怎么办?
Python的property解决了这个问题。
我们可以这样做
class Movie(object):
def __init__(self, title, description, score):
self.title = title
self.description = description
self.score = score
self.ticket = ticket
@property
def score(self):
return self.__score @score.setter
def score(self, score):
if score < 0:
raise ValueError("Negative value not allowed:{}".format(score))
self.__score = score @score.deleter
def score(self):
raise AttributeError("Can not delete score")
这样在任何地方修改score都会检测它是否小于0。
property的不足
对property来说,最大的缺点就是它们不能重复使用。举个例子,假设你想为ticket字段也添加非负检查。下面是修改过的新类:
class Movie(object):
def __init__(self, title, description, score, ticket):
self.title = title
self.description = description
self.score = score
self.ticket = ticket @property
def score(self):
return self.__score @score.setter
def score(self, score):
if score < 0:
raise ValueError("Negative value not allowed:{}".format(score))
self.__score = score @score.deleter
def score(self):
raise AttributeError("Can not delete score") @property
def ticket(self):
return self.__ticket @ticket.setter
def ticket(self, ticket):
if ticket < 0:
raise ValueError("Negative value not allowed:{}".format(ticket))
self.__ticket = ticket @ticket.deleter
def ticket(self):
raise AttributeError("Can not delete ticket")
可以看到代码增加了不少,但重复的逻辑也出现了不少。虽然property可以让类从外部看起来接口整洁漂亮,但是却做不到内部同样整洁漂亮。
描述符登场
什么是描述符?
一般来说,描述符是一个具有绑定行为的对象属性,其属性的访问被描述符协议方法覆写。这些方法是__get__()、__set__()和__delete__(),一个对象中只要包含了这三个方法中的至少一个就称它为描述符。
描述符有什么作用?
The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance, a.x has a lookup chain starting witha.__dict__['x'], then type(a).__dict__['x'], and continuing through the base classes of type(a) excluding metaclasses. If the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined.-----摘自官方文档
简单的说描述符会改变一个属性的基本的获取、设置和删除方式。
先看如何用描述符来解决上面 property逻辑重复的问题。
class Integer(object):
def __init__(self, name):
self.name = name def __get__(self, instance, owner):
return instance.__dict__[self.name] def __set__(self, instance, value):
if value < 0:
raise ValueError("Negative value not allowed")
instance.__dict__[self.name] = value class Movie(object):
score = Integer('score')
ticket = Integer('ticket')
因为描述符优先级高并且会改变默认的get、set行为,这样一来,当我们访问或者设置Movie().score的时候都会受到描述符Integer的限制。
不过我们也总不能用下面这样的方式来创建实例。
a = Movie()
a.score = 1
a.ticket = 2
a.title = 'test'
a.descript = '...'
这样太生硬了,所以我们还缺一个构造函数。
class Integer(object):
def __init__(self, name):
self.name = name def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__[self.name] def __set__(self, instance, value):
if value < 0:
raise ValueError('Negative value not allowed')
instance.__dict__[self.name] = value class Movie(object):
score = Integer('score')
ticket = Integer('ticket') def __init__(self, title, description, score, ticket):
self.title = title
self.description = description
self.score = score
self.ticket = ticket
这样在获取、设置和删除score和ticket的时候都会进入Integer的__get__、__set__,从而减少了重复的逻辑。
现在虽然问题得到了解决,但是你可能会好奇这个描述符到底是如何工作的。具体来说,在__init__函数里访问的是自己的self.score和self.ticket,怎么和类属性score和ticket关联起来的?
描述符如何工作
看官方的说明
If an object defines both __get__() and __set__(), it is considered a data descriptor. Descriptors that only define __get__() are called non-data descriptors (they are typically used for methods but other uses are possible).
Data and non-data descriptors differ in how overrides are calculated with respect to entries in an instance’s dictionary. If an instance’s dictionary has an entry with the same name as a data descriptor, the data descriptor takes precedence. If an instance’s dictionary has an entry with the same name as a non-data descriptor, the dictionary entry takes precedence.
The important points to remember are:
- descriptors are invoked by the
__getattribute__()method - overriding
__getattribute__()prevents automatic descriptor calls object.__getattribute__()andtype.__getattribute__()make different calls to__get__().- data descriptors always override instance dictionaries.
- non-data descriptors may be overridden by instance dictionaries.
类调用__getattribute__()的时候大概是下面这样子:
def __getattribute__(self, key):
"Emulate type_getattro() in Objects/typeobject.c"
v = object.__getattribute__(self, key)
if hasattr(v, '__get__'):
return v.__get__(None, self)
return v
下面是摘自国外一篇博客上的内容。
Given a Class “C” and an Instance “c” where “c = C(…)”, calling “c.name” means looking up an Attribute “name” on the Instance “c” like this:
- Get the Class from Instance
- Call the Class’s special method
__getattribute__. All objects have a default__getattribute__
Inside __getattribute__
- Get the Class’s
__mro__as ClassParents - For each ClassParent in ClassParents
- If the Attribute is in the ClassParent’s
__dict__ - If is a data descriptor
- Return the result from calling the data descriptor’s special method
__get__()
- Return the result from calling the data descriptor’s special method
- Break the for each (do not continue searching the same Attribute any further)
- If the Attribute is in the ClassParent’s
- If the Attribute is in Instance’s
__dict__- Return the value as it is (even if the value is a data descriptor)
- For each ClassParent in ClassParents
- If the Attribute is in the ClassParent’s
__dict__ - If is a non-data descriptor
- Return the result from calling the non-data descriptor’s special method
__get__()
- Return the result from calling the non-data descriptor’s special method
- If it is NOT a descriptor
- Return the value
- If the Attribute is in the ClassParent’s
- If Class has the special method
__getattr__- Return the result from calling the Class’s special method
__getattr__.
- Return the result from calling the Class’s special method
我对上面的理解是,访问一个实例的属性的时候是先遍历它和它的父类,寻找它们的__dict__里是否有同名的data descriptor如果有,就用这个data descriptor代理该属性,如果没有再寻找该实例自身的__dict__,如果有就返回。任然没有再查找它和它父类里的non-data descriptor,最后查找是否有__getattr__
描述符的应用场景
python的property、classmethod修饰器本身也是一个描述符,甚至普通的函数也是描述符(non-data discriptor)
django model和SQLAlchemy里也有描述符的应用
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True) def __init__(self, username, email):
self.username = username
self.email = email def __repr__(self):
return '<User %r>' % self.username
后记
只有当确实需要在访问属性的时候完成一些额外的处理任务时,才应该使用property。不然代码反而会变得更加啰嗦,而且这样会让程序变慢很多。
参考文章:
https://docs.python.org/3.5/howto/descriptor.html
http://www.betterprogramming.com/object-attribute-lookup-in-python.html
http://stackoverflow.com/questions/14787334/confused-with-getattribute-and-setattribute-in-python
http://www.jianshu.com/p/250f0d305c35
http://www.geekfan.net/7862/
如何正确地使用Python的属性和描述符的更多相关文章
- Python中属性和描述符的简单使用
Python的描述符和属性是接触到Python核心编程中一个比较难以理解的内容,自己在学习的过程中也遇到过很多的疑惑,通过google和阅读源码,现将自己的理解和心得记录下来,也为正在为了该问题苦恼的 ...
- python高级编程之描述符与属性03
# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #属性Property #提供了一个内建描述符类型,它知道如何将一个 ...
- Python笔记(4)类__属性与描述符
部分参考自:http://www.geekfan.net/7862/ 新式类与经典类 2和3不一样,3都是新式类. 新式类和经典类的区别: class A: #classic class " ...
- python高级编程之描述符与属性02
# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #元描述符 #特点是:使用宿主类的一个或者多个方法来执行一个任务,可 ...
- Python 为什么要使用描述符?
学习 Python 这么久了,说起 Python 的优雅之处,能让我脱口而出的, Descriptor(描述符)特性可以排得上号. 描述符 是Python 语言独有的特性,它不仅在应用层使用,在语言的 ...
- 90% 的 Python 开发者不知道的描述符应用
经过上面的讲解,我们已经知道如何定义描述符,且明白了描述符是如何工作的. 正常人所见过的描述符的用法就是上篇文章提到的那些,我想说的是那只是描述符协议最常见的应用之一,或许你还不知道,其实有很多 Py ...
- Python进阶——什么是描述符?
本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理 在 Python 开发中,你可能听说过「描述符」这个概念,由于我们很少直接使用它,所以大部分开发人员 ...
- python基础学习之描述符和装饰器
描述符的了解: 描述符协议: python描述符是一个"绑定行为"的对象属性,在描述符协议中,它可以通过方法重写属性的访问.这些方法有: __get__, __set__, 和__ ...
- Python属性、方法和类管理系列之----描述符类
什么是描述符类? 根据鸭子模型理论,只要具有__get__方法的类就是描述符类. 如果一个类中具有__get__和__set__两个方法,那么就是数据描述符,. 如果一个类中只有__get__方法,那 ...
随机推荐
- 【转】WMI使用的WIN32_类库名
ShadowBy--Win32_ShadowContext--Win32_ShadowCopy--Win32_ShadowDiffVolumeSupport--Win32_ShadowFor--Win ...
- python3倒叙字符串
google测试工程师的一道题: 设计一个函数,使用任意语言,完成以下功能: 一个句子,将句子中的单词全部倒排过来,但单词的字母顺序不变.比如,This is a real world,输出结果为 w ...
- StringBuilder与StringBuffer的区别(转)
相信大家看到过很多比较String和StringBuffer区别的文章,也明白这两者的区别,然而自从Java 5.0发布以后,我们的比较列表上将多出一个对象了,这就是StringBuilder类.St ...
- xml学习笔记一(概述)
XML 被设计用来传输和存储数据. HTML 被设计用来显示数据. 什么是 XML? XML 指可扩展标记语言(EXtensible Markup Language) XML 是一种标记语言,很类似 ...
- Intellij IDEA 的使用(创建项目、导入项目、同时部署多个项目、JRebel)等常见eclipse、myeclipse换idea必看
第一篇:Intellij IDEA 的使用 1.黑色主题 中文乱码修改 2.WEB项目的部署 以及自动编译 3.多项目的同时部署 4.相关插件提高工作效率 1.JRebel插件 实现热部署 2.Tas ...
- centos6.5 安装iptables
阿里云默认是没有安装iptables 安装 yum install -t iptables yum install iptables-services 检查iptables服务的状态 service ...
- ASP.NET MVC 程序 报错“CS0012: 类型“System.Data.Objects.DataClasses.EntityObject”在未被引用的程序集中定义”的解决办法
运行MVC程序,具体报错信息如下: 解决方法: 打开Web.config在assemblies下加入<add assembly="System.Data.Entity, Version ...
- MySql远程连接无法打开解决办法
1.改表法. 请使用mysql管理工具,如:SQLyog Enterprise 可能是你的帐号不允许从远程登陆,只能在localhost.这个时候只要在localhost的那台电脑使用mysql管理工 ...
- web首页设置如下代码可判断用户是用什么设备登录的?
var OnePage=true;//用来判断staticHtml.js中首页登入的信息判断var _mobileUrl = "http://a.abc.com";//手机用户通过 ...
- $(function(){})和$(document).ready(function(){})
document.ready和onload的区别——JavaScript文档加载完成事件 页面加载完成有两种事件 一是ready,表示文档结构已经加载完成(不包含图片等非文字媒体文件) 二是onloa ...