在问题What does the "yield" keyword do? ,我发现正在使用一种我不认为有效的 Python 语法。这个问题很老,而且有很多选票,所以我很惊讶至少没有人对这个函数定义发表评论:
def node._get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
我试图对这种语法进行评估:
- 将属性分配给类或对象
- 重新定义导入模块的功能
到目前为止失败了
SyntaxError: invalid syntax
我查找了 link (maybe outdated)在问题中给出,并在网上搜索 def
的用法,但我没有找到任何解释这种“点名”模式的内容。我正在使用 Python 3,也许这是 Python 2 的一个特性?
这个语法是否(或曾经)有效,如果是,那意味着什么?
最佳答案
不,语法无效。通过查看文档很容易证明。在 Python 2 中,标识符由以下 rules 构造:
identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
在 Py3 中,除了扩展到 Unicode 字符的范围外,规则或多或少是相同的。
看来作者大概是这个意思
class Node:
...
def _get_child_candidates(self, ...):
...
关于python - 是否可以在 Python 中定义一个带点名的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39871227/