Python的内置函数之getattr

Python的内置函数之getattr

属性介绍

getattr(object, name[,default])

  • 返回object的命名属性的值。 name必须是一个字符串。 如果字符串是对象属性之一的名称,则结果是该属性的值。
  • 例如,getattr(x,‘foobar’)等同于x.foobar。
  • 如果named属性不存在,则返回default(如果提供),否则引发AttributeError。

Property introduction

getattr(object, name[,default])

  • Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute.
  • For example, getattr(x, 'foobar') is equivalent to x.foobar.
  • If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Examples

from django.conf import settings

def __init__(self, *args, **kwargs):
    super(Login, self).__init__(*args, **kwargs)
    fields_ordering = ['username', 'password', 'region']
    if getattr(settings, 'LOGIN_CAPTCHA_ENABLE', False):
        self.fields['captcha'] = CaptchaField(
            label=_("Captcha"),
            error_messages={"invalid": "Invalid Captcha"})
        fields_ordering = ['username', 'password', 'captcha', 'region']

if getattr(settings, 'LOGIN_CAPTCHA_ENABLE', False):中的getattr(settings, 'LOGIN_CAPTCHA_ENABLE', False)表示在django的settings文件中的LOGIN_CAPTCHA_ENABLE命令的值,如果这个值没有在settings文件中进行命名,就返回default值为False。


JackDan Thinking

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值