我知道不能替换“del”(“return”等)关键字的行为,但我不明白为什么不能这样做:
myobj.del(mystr)
解析器会将它与什么混淆?有办法允许吗?
当然,我可以使用不同的名称,但我想对 AWS 工具 s3cmd 进行一些自定义包装,并执行类似 s3cmd.del("s3://some/bucket/")
并让“del”由我的 s3cmd 类中的 __getattr__
处理...所以“del”这个名字我真的很乐意设法使用。
最佳答案
那是因为这样的词是关键词。 Python 中的关键字是不能用作普通标识符的保留字。
列表包括from the doc function keyword
>>> import keyword
>>> import pprint
>>> pprint.pprint(keyword.kwlist)
['and',
'as',
'assert',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'exec',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'not',
'or',
'pass',
'print',
'raise',
'return',
'try',
'while',
'with',
'yield']
Konrad's comment 中很好地提到了原因。
There’s nothing magical about keywords. However, it makes parsers vastly easier to write when disallowing keywords for identifiers. In particular, it makes it easier to provide human-readable error messages for parse errors, because the parser is able to infer more context about the error.
关于python - 为什么具有名为 "del"、 "return"等的对象属性是语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29346945/