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 tox.foobar
. - If the named attribute does not exist,
default
is returned if provided, otherwiseAttributeError
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