当前位置: 移动技术网 > IT编程>脚本编程>Python > python __getattra__()

python __getattra__()

2019年04月30日  | 移动技术网IT编程  | 我要评论

阐教玉鼎异界纵横,尸官经年,无法再见的时光

官网解释:

  • 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中没有这个属性

getattr1.png

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

getattr5.png

print s.score   #class中没有这个属性

getattr3.png

print s.gg       #class中没有这个属性

getattr4.png

 

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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网