zoukankan      html  css  js  c++  java
  • 关于python魔法方法 __getattr__ 的一些理解

    引言

    关于_getattr_,首先我们从一个例子入手;

    class Dict(dict):
    
        def __init__(self, **kw):
            super().__init__(**kw)
    
        def __getattr__(self, key):
            try:
                return self[key]
            except KeyError:
                raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
    
        def __setattr__(self, key, value):
            self[key] = value

    看到里面有一个 def _getattr_(self, key):是不是不理解

    概念介绍

    _getattr__是python里的一个内建函数,可以很方便地动态返回一个属性;
    当调用不存在的属性时,Python会试图调用__getattr__(self,'key')来获取属性,并且返回key;

    class Student(object):  
        def__getattr__(self, attrname):  
            ifattrname =="age":  
                return40  
            else:  
                raiseAttributeError, attrname  
       
    x =Student()  
    print(x.age)       #40  
    print(x.name)      #error text omitted.....AttributeError, name  

    这里定义一个Student类和实例x,并没有属性age,当执行x.age,就调用_getattr_方法动态创建一个属性;

    下面展示一个_getattr_经典应用的例子,可以调用dict的键值对

     class ObjectDict(dict):
     2     def __init__(self, *args, **kwargs):
     3         super(ObjectDict, self).__init__(*args, **kwargs)
     4 
     5     def __getattr__(self, name):
     6         value =  self[name]
     7         if isinstance(value, dict):
     8             value = ObjectDict(value)
     9         return value
    10 
    11 if __name__ == '__main__':
    12     od = ObjectDict(asf={'a': 1}, d=True)
    13     print od.asf, od.asf.a     # {'a': 1} 1
    14     print od.d                 # True
  • 相关阅读:
    vim删除以#,空格开头的行
    Element-ui 中对表单进行验证
    VUE页面实现加载外部HTML方法
    vue-cli2嵌入html
    文字环绕图片
    LocalDate计算两个日期相差天数
    springboot+vue脚手架使用nginx前后端分离
    通过 Netty、ZooKeeper 手撸一个 RPC 服务
    Spring Native 项目,把 Spring 项目编译成原生程序!
    印象笔记吐槽
  • 原文地址:https://www.cnblogs.com/freezhi/p/7699045.html
Copyright © 2011-2022 走看看