简体   繁体   English

Python中的代码块

[英]Blocks of code in Python

Can you elaborate on the current state of "blocks" (in the Ruby sense) in Python? 你能详细说明Python中“块”(在Ruby意义上)的当前状态吗?

What are the language constructs that exist in Python? Python中存在哪些语言结构? How do they compare to other languages (like Ruby, Smalltalk, [insert more])? 他们如何与其他语言(如Ruby,Smalltalk,[插入更多])进行比较? Or does Python lack such constructs? 或者Python缺乏这样的结构?

I have so far understood the lambda thing; 到目前为止,我已经了解了lambda事情; it is only one-line, but maybe it comes close. 它只是单行,但也许它接近。 What about "decorators" and yield in this context? 在这种情况下,“装饰者”和yield怎么样?

I am also using old Python versions in some projects. 我也在一些项目中使用旧的Python版本。 Which constructs were introduced in which Python version (2.5, 2.6, etc.) or are planned in future versions? 在Python版本(2.5,2.6等)或未来版本中计划引入哪些构造?

Can you link interesting articles on the subject that explain this stuff for Python and also comparing to other languages and could be interesting for someone who wants to extend basic Python knowledge? 您是否可以链接有关该主题的有趣文章来解释Python的这些内容以及与其他语言进行比较,对于想要扩展基本Python知识的人来说可能会有趣吗?

Functions are the first-class members in Python: 函数是Python中的第一类成员:

def add(x, y):
    return x + y

a = add          # Bind
b = a(34, 1)     # Call

So you can pass functions around all you want. 所以你可以传递你想要的所有功能。 You can do the same with any callable object in Python. 您可以对Python中的任何可调用对象执行相同的操作。

lambda is the closest equivalent to a Ruby block, and the restriction to one line is intentional . lambda是最接近Ruby块的等价物,对一行的限制是故意的 It is typically argued that multiline anonymous functions (blocks, in Ruby) are usually less readable than defining the function somewhere with a name and passing that, as illustrated in SilentGhost's answer . 通常认为多行匿名函数(Ruby中的块) 通常不如使用名称定义函数并传递它的可读性,如SilentGhost的答案所示

There are good discussions on comp.lang.python that compare to other languages: 关于comp.lang.python的讨论与其他语言相比有很好的讨论:

The def is equivalent of an assignment statement which only binds the function object to the object reference variable. def等同于赋值语句,它只将函数对象绑定到对象引用变量。

The object reference variable can then be used to call the function object to execute. 然后可以使用对象引用变量来调用要执行的函数对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM