>> foo.@%#$% Syn-6ren">
gpt4 book ai didi

python - setattr 接受无效标识符

转载 作者:行者123 更新时间:2023-12-03 00:19:32 26 4
gpt4 key购买 nike

这就是我的意思:

>>> class Foo:
pass

>>> foo = Foo()
>>> setattr(foo, "@%#$%", 10)
>>> foo.@%#$%
SyntaxError: invalid syntax
>>> getattr(foo, "@%#$%")
10
>>> foo.__dict__
{'@%#$%': 10}

我查了一下,它在 python 2 的问题跟踪器上被提出了两次:

https://bugs.python.org/issue14029

https://bugs.python.org/issue25205

还有一次是针对 python 3 的:

https://bugs.python.org/issue35105

他们坚称这不是一个错误。然而,这种行为显然不是故意的。它没有记录在任何版本中。对此有何解释?这似乎是一件很容易被忽视的事情,但感觉就像是把它扫到地毯下一样。那么,setattr 的行为背后是否有任何原因,或者它只是 python 的良性特质?

最佳答案

错误是在不应该发生时发生的事情,即,当某种通信方法禁止它发生时。如果没有文档说明这种情况不应该发生,那么(最坏的情况下)这就是一个特质,而不是一个错误。

Python 文档中似乎没有任何内容禁止不能与点符号一起使用的属性名称(毕竟,这只是语法糖),例如 foo.@%#$% 。唯一提到的是它们等效的示例,特别是:

For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

唯一的限制似乎是类本身是否允许:

The function assigns the value to the attribute, provided the object allows it.


在更正式的意义上,点符号被指定为 here :

6.3.1. Attribute references

An attribute reference is a primary followed by a period and a name: attributeref ::= primary "." identifier.

The primary must evaluate to an object of a type that supports attribute references, which most objects do. This object is then asked to produce the attribute whose name is the identifier. This production can be customized by overriding the __getattr__() method.

请注意该语法中的标识符,它具有超出实际属性名称的限制,如 here ,和PEP 3131更详细地了解了允许的内容(正是 PEP 将标识符移至非 ASCII 世界)。

由于标识符的限制比字符串中允许的限制更严格,因此 getattr/setattr 属性名称可以是点表示法中允许的名称的超集是有意义的。

关于python - setattr 接受无效标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59507867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com