1

http://effbot.org/zone/python-getattr.htm它指出

Python’s getattr function is used to fetch an attribute from an object, using 
a string object instead of an identifier to identify the
attribute. In other words, the following two statements are
equivalent:

    value = obj.attribute
    value = getattr(obj, "attribute")

让我感到困惑的是,我有一个带有动态类方法生成类的模块。我知道这一代有效,因为调用 __dict__ 返回

 >>> errors.__dict__
mappingproxy({'__module__': 'utils.errors', '__weakref__': 
<attribute '__weakref__' of 'errors' objects>,'404': <classmethod object at 
0x7fe547c23190>, '500': <classmethod object at 0x7fe547c23210>, '403': 
<classmethod object at 0x7fe547c23110>, '400': <classmethod object at 
0x7fe547c23090>})

让我困惑的是getattr起作用的脸,而直接调用属性却没有

>>> errors.404("asdf")
  File "<console>", line 1
    errors.404("asdf")
             ^
SyntaxError: invalid syntax
>>> getattr(errors,'404')("asdf")
{'error': 'Page Not Found', 'code': 404, 'message': 'asdf'}
4

1 回答 1

2

以数字开头的标识符不是有效的标识符 ( ref )。

于 2013-07-29T19:02:12.443 回答