python __getattra__()
官网解释:
object.
__getattr__
(self, name)Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for
self
).name
is the attribute name. This method should return the (computed) attribute value or raise anAttributeError
exception.
当我们想调用Class中某些东西,而Class中没有,解释器铁定报错,停止运行,那有人就想了:真麻烦,每次都要重新执行一遍,如果当我调用错了内容,程序能把我这个错误当默认程序执行,而不停止我程序运行就好了。so,为了解决这类问题,就出来了__getattr__这个函数了。
我猜的,因为解决程序困难也是一种需求。
看没有__getattr的出错调用:
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self):
self.name = 'Michael'
s = Student()
print s.name
print s.score #Class中没有这个属性
look, 第一个print正常执行,第二个由于Class中没有这个属性,所以就报错了。
再看,带__getattr__的Class:
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self):
self.name = 'Michael'
def __getattr__(self, other):
if other=='score':
return 99
s = Student()
print s.name
print s.score #Class中没有这个属性
print s.gg #Class中没有这个属性
look again, print 的score 和 gg 在Class中都没有定义,但都有输出。因为程序往__getattr__中找,刚刚好定义了一个字符判断 if other=='score':, 所以输出了99 ,而gg一个字都没提,就默认输出None了。是不是感觉以后码程序的时候再也不用担心程序停止运行了。
※发现的强大的链式调用写法:
class Chain(object): def __init__(self, path=''): self._path = path def __getattr__(self, path): return Chain('%s/%s' % (self._path, path)) #调用自己 def __str__(self): return self._path __repr__ = __str__ f = Chain() print (f.www.anc.do.glob)
结果:
/www/anc/do/glob
最新文章
- winkawaks模拟器
- Linux内核分析——第七周学习笔记20135308
- 解决Windows Server 2003不认U盘或移动硬盘的问题
- 802.11 wireless 1(主要还是学习ccna wireless的体系)
- flash链接需要后台调用时的插入flash方法
- iOS - 应用程序国际化
- 启明星辰:安全管理平台(SOC)
- veridata实验例(3)验证veridata发现insert操作不会导致同步
- JVM-2.Class文件结构
- Core Java 谈谈 ThreadPoolExecutor
- c#判断外部可执行程序是否已打开(若未打开则打开)
- python文件转exe
- vm—win7
- Win10系统的SurfacePro4如何重装系统-1 SurfacePro专用的PE
- (转)SQL知识_SQL Case when 的使用方法
- The project cannot be built until its prerequisite base-service is built. Cleaning and building all projects is recommended
- hdu3511 Prison Break 圆的扫描线
- 论文笔记——Channel Pruning for Accelerating Very Deep Neural Networks
- 20155336 2016-2017-2《JAVA程序设计》第七周学习总结
- mysqldump 备份单个数据库
热门文章
- 正则表达式-----re库
- C#中方法、类等的默认访问修饰符~
- C++——简单数据类型及布尔类型
- Jenkins - ERROR: Exception when publishing, exception message [Failed to connect session for config [IP(projectName)]. Message [Auth fail]]
- 【论文速读】Dan_Deng_AAAI2018_PixelLink_Detecting_Scene_Text_via_Instance_Segmentation
- 论文阅读(Lukas Neumann——【ICCV2017】Deep TextSpotter_An End-to-End Trainable Scene Text Localization and Recognition Framework)
- java实现人民币数字转大写(转)
- 从json-lib转成jackson的遇到的问题
- WebSphere应用程序更新方式
- 2018.5.15Html标签初学