python getattr_python Class:面向对象高级编程 __getattr__

官网解释: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 valueorraise anAttributeErrorexception.

当我们想调用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值