首页 > 其他 > 详细

__getattr__

时间:2017-04-29 19:32:35      阅读:256      评论:0      收藏:0      [点我收藏+]

当调用不存在的属性时,比如score,Python解释器会试图调用__getattr__(self, ‘score‘)来尝试获得属性,这样,
我们就有机会返回score的值:

class Student(object):
   def __init__(self):
       self.name = Michael
   def __getattr__(self, attr):
      if attr==score:
         return 99

当调用不存在的属性时,比如score,Python解释器会试图调用__getattr__(self, ‘score‘)来尝试获得属性,这样,
我们就有机会返回score的值:

>>> s = Student()
>>> s.name
Michael
>>> s.score
99

返回函数也是完全可以的:

class Student(object):
def __getattr__(self, attr):
if attr==age:
return lambda: 25

利用完全动态的__getattr__,我们可以写出一个链式调用:

 

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__
>>> Chain().status.user.timeline.list
/status/user/timeline/list

 

__getattr__

原文:http://www.cnblogs.com/dynas/p/6785799.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!