zoukankan      html  css  js  c++  java
  • python get() 和getattr()

    get()

    Python 字典 get() 函数返回指定键的值,如果值不在字典中返回默认值。
    语法: dict.get(key, default=None)
    实例1:
    d={'A':1,'b':2}
    m=d.get('C','Bob').lower()
    z=d.get('C','LUCY').lower() in ['a','B','V',3]
    print(m,z)      # bob False
    实例2
    MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')             
    

    getattr()

    getattr() 函数用于返回一个对象属性值。
    语法:getattr(object, name[, default])
    参数
    >> object -- 对象。
    >> name -- 字符串,对象属性。
    >> default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。
    
    实例
    >>>class A(object):
    ...     bar = 1
    ... 
    >>> a = A()
    >>> getattr(a, 'bar')        # 获取属性 bar 值
    1
    >>> getattr(a, 'bar2')       # 属性 bar2 不存在,触发异常
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'A' object has no attribute 'bar2'
    >>> getattr(a, 'bar2', 3)    # 属性 bar2 不存在,但设置了默认值
    3
    >>>
    
  • 相关阅读:
    Xshell 设置右键粘贴功能
    python中dict操作集合
    mac 设置网页字体
    博客收藏
    memcache 安装与简单使用
    mac安装homebrew
    Graphviz下载 使用
    jekyll 与hexo
    js 汉字排序
    初试gem
  • 原文地址:https://www.cnblogs.com/plusUltra/p/10572512.html
Copyright © 2011-2022 走看看