python __getattr__ 巧妙应用
class ObjectDict(dict):
def __init__(self, *args, **kwargs):
super(ObjectDict, self).__init__(*args, **kwargs) def __getattr__(self, name):
value = self[name]
if isinstance(value, dict):
value = ObjectDict(value)
return value if __name__ == '__main__':
od = ObjectDict(asf={'a': 1}, d=True)
print od.asf, od.asf.a # {'a': 1} 1
print od.d # True
class WidgetShowLazyLoad(object):
def fetch_complex_attr(self, attrname):
'''可能是比较耗时的操作, 比如从文件读取'''
return attrname def __getattr__(self, name):
if name not in self.__dict__:
self.__dict__[name] = self.fetch_complex_attr(name)
return self.__dict__[name] if __name__ == '__main__':
w = WidgetShowLazyLoad()
print 'before', w.__dict__
w.lazy_loaded_attr
print 'after', w.__dict__
import functools
class lazy_attribute(object):
""" A property that caches itself to the class object. """ def __init__(self, func):
functools.update_wrapper(self, func, updated=[])
self.getter = func def __get__(self, obj, cls):
value = self.getter(cls)
setattr(cls, self.__name__, value)
return value class Widget(object):
@lazy_attribute
def complex_attr_may_not_need(clz):
print 'complex_attr_may_not_need is needed now'
return sum(i*i for i in range(1000)) if __name__ == '__main__':
print Widget.__dict__.get('complex_attr_may_not_need') # <__main__.lazy_attribute object at 0x02B12450>
Widget.complex_attr_may_not_need # complex_attr_may_not_need is needed now
print Widget.__dict__.get('complex_attr_may_not_need') #
class adaptee(object):
def foo(self):
print 'foo in adaptee'
def bar(self):
print 'bar in adaptee' class adapter(object):
def __init__(self):
self.adaptee = adaptee() def foo(self):
print 'foo in adapter'
self.adaptee.foo() def __getattr__(self, name):
return getattr(self.adaptee, name) if __name__ == '__main__':
a = adapter()
a.foo()
a.bar()
class AlgoImpA(object):
def __init__(self):
self.obj_attr = 'obj_attr in AlgoImpA' def foo(self):
print 'foo in AlgoImpA' def bar(self):
print 'bar in AlgoImpA' class AlgoImpB(object):
def __init__(self):
self.obj_attr = 'obj_attr in AlgoImpB' def foo(self):
print 'foo in AlgoImpB' def bar(self):
print 'bar in AlgoImpB' class Algo(object):
def __init__(self):
self.imp_a = AlgoImpA()
self.imp_b = AlgoImpB()
self.cur_imp = self.imp_a def switch_imp(self):
if self.cur_imp == self.imp_a:
self.cur_imp = self.imp_b
else:
self.cur_imp = self.imp_a def __str__(self):
return 'Algo with imp %s' % str(self.cur_imp) def __getattr__(self, name):
return getattr(self.cur_imp, name) if __name__ == '__main__':
algo = Algo() print algo
print algo.obj_attr
algo.foo() algo.switch_imp() print algo
print algo.obj_attr
algo.bar()
Algo with imp <__main__.AlgoImpA object at 0x02AA2270>
obj_attr in AlgoImpA
foo in AlgoImpA
Algo with imp <__main__.AlgoImpB object at 0x02AA22B0>
obj_attr in AlgoImpB
bar in AlgoImpB
python __getattr__ 巧妙应用的更多相关文章
- python __getattr__ & __getattribute__ 学习
实例属性的获取和拦截, 仅对实例属性(instance, variable)有效, 非类属性 getattr: 适用于未定义的属性, 即该属性在实例中以及对应的类的基类以及祖先类中都不存在 1. 动态 ...
- Python - __getattr__和__getattribute__的区别
传送门 https://docs.python.org/3/reference/datamodel.html#object.__getattr__ https://docs.python.org/3/ ...
- 某校高中生利用Python,巧妙获取考试成绩,看到成绩后无言以对!
Python是非常有吸引力的编程语言,学习Python的不是帅哥就是美女.为什么这么说呢?因为我和我的女朋友都是学习Python认识的,小编肯定是帅哥,不用去怀疑,而且我眼光特高. 给大伙讲一个故事, ...
- python __getattr__
1.__getattr__ 方法的作用:当调用不存在的属性,就会调用__getattr__()方法: 当一般位置找不到attribute的时候,会调用getattr,返回一个值或AttributeEr ...
- python __getattr__ __setattr__
class Rectangle: def __init__(self): self.width = 0 self.height = 0 def __setattr__(self, key, value ...
- python __getattr__和 __getattribute__
__getattr__ 这个魔法函数会在类中查找不到属性时调用 class User: def __init__(self): self.info = 1 def __getattr__(self, ...
- Python中__get__, __getattr__, __getattribute__的区别及延迟初始化
本节知识点 1.__get__, __getattr__, __getattribute__的区别 2.__getattr__巧妙应用 3.延迟初始化(lazy property) 1.__get__ ...
- Python数据结构与算法设计总结篇
1.Python数据结构篇 数据结构篇主要是阅读[Problem Solving with Python]( http://interactivepython.org/courselib/static ...
- [leetcode]Permutations @ Python
原题地址:https://oj.leetcode.com/problems/permutations/ 题意: Given a collection of numbers, return all po ...
随机推荐
- Duilib XML嵌套
duilib使用嵌套xml可以简化代码的书写,有利于模块化的页面布局分解,duilib库的xml嵌套主要有两种方式 方式一.以创建控件的方式嵌套xml 在CreateControl(LPCTSTR p ...
- RabbitMQ消息队列系列教程(一)认识RabbitMQ
摘要 RabbitMQ是最为流行的消息中间件,是处理高并发业务的利器.本系列教程,将跟大家一起学习RabbitMQ. 目录 RabbitMQ是什么? RabbitMQ的特点是什么? 一.RabbitM ...
- 用原型代替PRD时,原型应该包含哪些内容
随着互联网节奏越来越快,传统的需求文档已经比较难适应市场的脚步,特别对于要求敏捷的团队来说,冗余而细致入微的需求文档已经成为包袱(这么长个文档领导也不会看呀).目前大多数团队更喜爱直接使用原型来代替需 ...
- openFace 人脸识别框架测试
openface 人脸识别框架 但个人感觉精度还是很一般 openface的githup文档地址:http://cmusatyalab.github.io/openface/ openface的安 ...
- .Net Core 2.0 EntityFrameworkCore CodeFirst入门教程
最近难得有时间闲下来,研究了一下.net core 2.0,总的来说,目前除了一些第三方的库不支持外,基本上可以满足我们的项目需求了! 我们就以一个网站开发为例,搭建一个简单的三层架构,先熟悉一下.n ...
- 【Mysql知识补充】
一.子查询 1.定义 子查询是将一个查询语句嵌套在另一个查询语句中.内层查询语句的查询结果,可以为外层查询语句提供查询条件.子查询中可以包含:IN.NOT IN.ANY.ALL.EXISTS 和 NO ...
- Webapi调用
C# webapi 路由名称不能跟area名称相同,否则出现404 action找不到的问题???
- 数据库 SQL Server2012安装步骤详解
这篇文章主要给大家讲解一下数据库SQL Server2012的安装步骤(若有雷同纯属巧合,还望谅解!) 在正式安装之前,我们需要进行两个设置: ① 首先需要关闭Windows防火墙,若不关闭,后续的安 ...
- Java爬虫实践--爬取CSDN网站图片为例
实现的效果,自动在工程下创建Pictures文件夹,根据网站URL爬取图片,层层获取.在Pictures下以网站的层级URL命名文件夹,用来装该层URL下的图片.同时将文件名,路径,URL插入数据库, ...
- 洛谷教主花园dp
洛谷-教主的花园-动态规划 题目描述 教主有着一个环形的花园,他想在花园周围均匀地种上n棵树,但是教主花园的土壤很特别,每个位置适合种的树都不一样,一些树可能会因为不适合这个位置的土壤而损失观赏价 ...