这段代码产生了一个TypeError,看起来就像文档描述的那样:
>>> def f(): pass
...
>>> f.func_globals = 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: readonly attribute
但是这个TypeError 真的是因为文档上说的而提出的吗?我真诚地怀疑它。我猜func_globals 实现只会引发TypeError,如果您尝试为其分配一些东西。
顺便说一句...
我实际上会在下一个示例中期望相同,但它是 AttributeError:
>>> class A(object):
... __slots__ = 'a',
...
>>> A().b = 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'b'
更新(Python 3)
以上是在 Python 2.7 中。在 Python 3 中,没有func_globals,所以这不适用(你可以给它赋值)。
Python 3 中的哪些属性函数在只读时似乎会引发 AttributeError。
>>> f.__globals__ = 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: readonly attribute
这对我来说很有意义。就 Python 3 而言,也许这部分文档只是一个遗物。