首页 > 代码库 > __getattr__

__getattr__

当调用不存在的属性时,比如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__