是否可以在Python中定义带有虚线名称的函数? [英] Is it possible to def a function with a dotted name in Python?

查看:64
本文介绍了是否可以在Python中定义带有虚线名称的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在问题中 "yield"关键字有什么作用? ,我发现正在使用我没想到有效的Python语法.这个问题很老,而且有很多票,所以让我感到惊讶的是,至少没有人对此功能定义发表评论:

In the question What does the "yield" keyword do?, I found a Python syntax being used that I didn't expect to be valid. The question is old and has a huge number of votes, so I'm surprised nobody at least left a comment about this function definition:

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  

我试图对这种语法进行评估的内容:

What I tried to get this sort of syntax evaluated:

  • 将属性分配给类或对象
  • 重新定义导入模块的功能

到目前为止

SyntaxError:语法无效

SyntaxError: invalid syntax

我查找了问题中给出的链接(可能已过时),并在网上搜索了用法定义为 def ,但没有发现任何解释这种点名"模式的信息.我正在使用Python 3,也许这是Python 2的功能?

I looked up the link (maybe outdated) given in the question, and searched the web for the usage of def, but I found nothing explaining this "dotted name" pattern. I'm using Python 3, maybe this is a feature of Python 2?

(如果曾经)此语法是否有效?

推荐答案

否,语法无效.通过检查文档很容易证明.在Python 2中,标识符是由以下规则构造的:

No, the syntax is not valid. It is easy to prove by checking the documentation. In Python 2, an identifier is constructed by the following rules:

identifier ::=  (letter|"_") (letter | digit | "_")*
letter     ::=  lowercase | uppercase
lowercase  ::=  "a"..."z"
uppercase  ::=  "A"..."Z"
digit      ::=  "0"..."9"

在Py3中,规则基本相同,除了扩展到Unicode字符范围之外.

In Py3 the rules are more or less the same, beside being expanded up to the range of Unicode characters.

作者看来可能是这样的意思

It seems that the author probably meant something like

class Node:
    ...
    def _get_child_candidates(self, ...):
        ...

这篇关于是否可以在Python中定义带有虚线名称的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆