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