官网解释:

  • object.__getattr__(selfname)

  • 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 an AttributeError 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

最新文章

  1. winkawaks模拟器
  2. Linux内核分析——第七周学习笔记20135308
  3. 解决Windows Server 2003不认U盘或移动硬盘的问题
  4. 802.11 wireless 1(主要还是学习ccna wireless的体系)
  5. flash链接需要后台调用时的插入flash方法
  6. iOS - 应用程序国际化
  7. 启明星辰:安全管理平台(SOC)
  8. veridata实验例(3)验证veridata发现insert操作不会导致同步
  9. JVM-2.Class文件结构
  10. Core Java 谈谈 ThreadPoolExecutor
  11. c#判断外部可执行程序是否已打开(若未打开则打开)
  12. python文件转exe
  13. vm—win7
  14. Win10系统的SurfacePro4如何重装系统-1 SurfacePro专用的PE
  15. (转)SQL知识_SQL Case when 的使用方法
  16. The project cannot be built until its prerequisite base-service is built. Cleaning and building all projects is recommended
  17. hdu3511 Prison Break 圆的扫描线
  18. 论文笔记——Channel Pruning for Accelerating Very Deep Neural Networks
  19. 20155336 2016-2017-2《JAVA程序设计》第七周学习总结
  20. mysqldump 备份单个数据库

热门文章

  1. 正则表达式-----re库
  2. C#中方法、类等的默认访问修饰符~
  3. C++——简单数据类型及布尔类型
  4. Jenkins - ERROR: Exception when publishing, exception message [Failed to connect session for config [IP(projectName)]. Message [Auth fail]]
  5. 【论文速读】Dan_Deng_AAAI2018_PixelLink_Detecting_Scene_Text_via_Instance_Segmentation
  6. 论文阅读(Lukas Neumann——【ICCV2017】Deep TextSpotter_An End-to-End Trainable Scene Text Localization and Recognition Framework)
  7. java实现人民币数字转大写(转)
  8. 从json-lib转成jackson的遇到的问题
  9. WebSphere应用程序更新方式
  10. 2018.5.15Html标签初学