zoukankan      html  css  js  c++  java
  • __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'
  • 相关阅读:
    Vue Hooks
    React初识-Hooks
    React-JSX初识
    css基础知识
    发布-订阅者模式
    Map和Set
    数据类型
    tcp三次握手以及tcp三次握手一句话总结
    网页布局相关
    浏览器渲染页面的流程
  • 原文地址:https://www.cnblogs.com/dynas/p/6785799.html
Copyright © 2011-2022 走看看