python - 为什么具有名为 "del"、 "return"等的对象属性是语法错误?

标签 python

我知道不能替换“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/

相关文章:

python - 将多索引 pandas 连接成单个 pandas

python - 从 C 代码调用 numpy 函数

python - 代码的行为不像是在满足条件时? [ python 3]

python - 使用 NumPy 进行快速傅立叶变换 : why it looks like this?

Python条件字典理解

python - 如何使用 pyspark SQL 获取基于时间的累计值?

python - 在哪里为 Django 项目设置 Python 环境属性?

python - zip(*) 是如何生成 n-gram 的?

python elementtree xml追加

python - pd.DatetimeIndex.weekday 和 pd.DatetimeIndex.dayofweek 有什么区别