Python开发【笔记】: __get__和__getattr__和__getattribute__区别
引言:
1.object.__getattr__(self, name)
当一般位置找不到attribute的时候,会调用getattr,返回一个值或AttributeError异常。
2.object.__getattribute__(self, name)
无条件被调用,通过实例访问属性。如果class中定义了__getattr__(),则__getattr__()不会被调用(除非显示调用或引发AttributeError异常)
3.object.__get__(self, instance, owner)
如果class定义了它,则这个class就可以称为descriptor。owner是所有者的类,instance是访问descriptor的实例,如果不是通过实例访问,而是通过类访问的话,instance则为None。(descriptor的实例自己访问自己是不会触发__get__,而会触发__call__,只有descriptor作为其它类的属性才有意义。)(所以下文的d是作为C2的一个属性被调用)
示例1:
# __getattribute__、__getattr__、__get__
class C(object):
a = 'abc' def __getattribute__(self, *args, **kwargs):
print("__getattribute__() is called")
return object.__getattribute__(self, *args, **kwargs) def __getattr__(self, name):
print("__getattr__() is called ")
return name + " from getattr" def __get__(self, instance, owner):
print("__get__() is called", instance, owner)
return self def foo(self, x):
print(x) class C2(object):
d = C() if __name__ == '__main__':
c = C()
c2 = C2()
print(c.a)
# __getattribute__() is called
# abc
print(c.b)
# __getattribute__() is called
# __getattr__() is called
# b from getattr
c2.d
# __get__() is called <__main__.C2 object at 0x0000007D8B0E7D68> <class '__main__.C2'>
print(c2.d.a)
# __get__() is called <__main__.C2 object at 0x000000B6FDAE7D68> <class '__main__.C2'>
# __getattribute__() is called
# abc
示例2:
class LazyProperty:
def __init__(self, method):
print(method,method.__name__)
self.method = method
self.method_name = method.__name__
# print('function overriden: {}'.format(self.method))
# print("function's name: {}".format(self.method_name))
def __get__(self, obj, cls):
print('__get__',obj,cls)
if not obj:
return None
value = self.method(obj)
# print('value {}'.format(value))
setattr(obj, self.method_name, value)
return value
class Jefrey:
def __init__(self):
self.x = 'foo'
self.y = 'bar'
self._resource = None
@LazyProperty
def resource(self):
print('initializing self._resource which is: {}'.format(self._resource))
self._resource = tuple(range(5)) # 代价大的
return self._resource
def main():
t = Jefrey()
# <function Jefrey.resource at 0x00000089690E6730> resource
print(t.x)
print(t.y)
# foo
# bar
# 做更多的事情。。。
print(t.resource)
# __get__ <__main__.Jefrey object at 0x00000089690E7C50> <class '__main__.Jefrey'>
# initializing self._resource which is: None
# (0, 1, 2, 3, 4)
print(t.resource)
# (0, 1, 2, 3, 4)
if __name__ == '__main__':
main()
Python开发【笔记】: __get__和__getattr__和__getattribute__区别的更多相关文章
- python开发笔记-通过xml快捷获取数据
今天在做下python开发笔记之如何通过xml快捷获取数据,下面以调取nltk语料库为例: import nltk nltk.download() showing info https://raw.g ...
- python开发笔记-python调用webservice接口
环境描述: 操作系统版本: root@9deba54adab7:/# uname -a Linux 9deba54adab7 --generic #-Ubuntu SMP Thu Dec :: UTC ...
- 飘逸的python - __get__ vs __getattr__ vs __getattribute__以及属性的搜索策略
差别: __getattribute__:是无条件被调用.对不论什么对象的属性訪问时,都会隐式的调用__getattribute__方法,比方调用t.__dict__,事实上运行了t.__getatt ...
- python开发笔记-Python3.7+Django2.2 Docker镜像搭建
目标镜像环境介绍: 操作系统:ubuntu16.04 python版本:python 3.7.4 django版本:2.2 操作步骤: 1. 本地安装docker环境(略)2. 拉取ubunut指定 ...
- python开发笔记之zip()函数用法详解
今天分享一篇关于python下的zip()函数用法. zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素按顺序组合成一个tuple,每个tuple中包含的是原 ...
- Python开发笔记之正则表达式的使用
查找正则表达式 import re re_txt = re.compile(r'(\d)*.txt') m = re_txt.search(src) if not m == None: m.group ...
- python开发笔记-类
类的基本概念: 问题空间:问题空间是问题解决者对一个问题所达到的全部认识状态,它是由问题解决者利用问题所包含的信息和已贮存的信息主动的地构成的. 初始状态:一开始时的不完全的信息或令人不满意的状况: ...
- Python开发笔记之-浮点数传输
操作系统 : CentOS7.3.1611_x64 gcc版本 :4.8.5 Python 版本 : 2.7.5 思路如下 : 1.将浮点数a通过内存拷贝,赋值给相同字节的整型数据b: 2.将b转换为 ...
- Python开发笔记:网络数据抓取
网络数据获取(爬取)分为两部分: 1.抓取(抓取网页) · urlib内建模块,特别是urlib.request · Requests第三方库(中小型网络爬虫的开发) · Scrapy框架(大型网络爬 ...
随机推荐
- PHP中替换换行符方法总结
<?php header("content-type:text/html;charset=utf-8"); $str = "aaaa bbbb cccc dddd& ...
- sp_configure命令开启组件Agent XPs,数据库计划(Maintenance Plan)
新建“计划(Maintenance Plan)”时,记得执行计划需把SQL的“代理服务(SQL Server Agent)”也开启 出现对话框:“SQL Server 阻止了对组件 'Agent XP ...
- [转]查看处于被锁状态的表:v$locked_object dba_objects v$session all_objects v$sqlarea v$lock
oracle官网当一个用户发出select..for update的错作准备对返回的结果集进行修改时,如果结果集已经被另一个会话锁定,就是发生阻塞.需要等另一个会话结束之后才可继续执行.可以通过发出 ...
- chrome浏览器开发者工具使用教程[转]
转自:http://www.cr173.com/html/16930_1.html 更多资源:https://developers.google.com/chrome-developer-tools/ ...
- linux中nmcli命令详解
https://www.iyunv.com/thread-269695-1-1.html http://www.178linux.com/44668
- 【iOS与EV3混合机器人编程系列之三】编写EV3 Port Viewer 应用监測EV3port数据
在前两篇文章中,我们对iOS与EV3混合机器人编程做了一个主要的设想.而且介绍了要完毕项目所需的软硬件准备和知识准备. 那么在今天这一篇文章中,我们将直接真正開始项目实践. ==第一个项目: EV3 ...
- LeetCode——Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values. For example: Given binary t ...
- JBPM4.4_执行流程实例
1. 执行流程实例 1.1. 启动流程实例 说明:流程实例创建后,直接就到开始活动后的第一个活动,不会在开始活动停留. 1.1.1. 示例代码1:使用指定key的最新版本的流程定义启动流程实例 Pro ...
- 08python之列表的常用方法
列表list是python常用的数据类型,需要掌握以下常用方法: name_list = ['alex','tenglan','65brother'] 这个变量和之前的变量只存一个数字或字符串,这个列 ...
- Linux基本监控项目
1.网卡流量 (统计网卡TX(发送)RX(接受)流量脚本) 使用 Nagios 来监控网卡流量 2013/01/31 Nagios, 网卡 监控统计与日志分析 评论 2,272 下载地址为:che ...