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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章