python - 是否可以在 Python 中定义一个带点名的函数?

标签 python function syntax-error

在问题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/

相关文章:

python - python中的hackerrank平均函数

php - php中的动态函数名

c - 运行函数的指针,其中变量是结构的变量

python-3.x - 为什么这在我的request.get变量上显示为语法错误?

syntax-error - VHDL : Error in when conditional

python - 如何完全或部分匹配 python 中的正则表达式

python - 提交后如何仅清除表单中的特定字段?

python - 如何编写可以与 swift 可执行文件的输入和输出进行通信的 python 脚本?

python - Pytorch 运行时错误 : element 0 of tensors does not require grad and does not have a grad_fn

ruby-on-rails - 为什么带有额外参数的 button_tag 会出错?