2013-07-29 25 views
1

返回函数在http://effbot.org/zone/python-getattr.htm它指出Python对象只GETATTR

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 0x7fe547c>, '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'} 

回答

2

标识符开始与一些无效标识符(ref)。

+0

看起来很奇怪,他们会允许无效标识符setattr。 – user1876508

+0

我宁愿说这很奇怪,他们会允许点式属性查找,同时限制允许查询的属性名称。它只是'__getattribute__'的语法糖。 –