Python vars 嵌套赋值 [英] Python vars nested assignment

查看:25
本文介绍了Python vars 嵌套赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题所讲内容的示例:

#seen 在 PyOpenGL 的演示中# http://PyOpenGL.sourceforge.net/大小 = self.size = self.GetClientSize()

这是干什么用的?它是如何工作的以及何时使用它?

我的想法是这允许将第三项的值分配给第一项和第二项......如果是这样,我们可以嵌套无限数量的变量.

解决方案

这是一个链式作业.您将 sizeself.size 都设置为 self.GetClientSize() 的返回值.

您可以放弃链接分配:

<预><代码>>>>foo = bar = 垃圾邮件 = 鸡蛋 = 'frobnicators'>>>富'frobnicators'>>>酒吧,垃圾邮件,鸡蛋('frobnicators', 'frobnicators', 'frobnicators')

注意右边的表达式只计算一次,它的值从左到右分配给所有左边的变量.

如果您反编译 Python 字节码,则最容易看到这一点:

<预><代码>>>>导入文件>>>定义 foo():... bar = baz = 鸡蛋 = '垃圾邮件'...>>>dis.dis(foo)2 0 LOAD_CONST 1 ('垃圾邮件')3 DUP_TOP4 STORE_FAST 0(条形)7 DUP_TOP8 STORE_FAST 1 (baz)11 STORE_FAST 2(鸡蛋)14 LOAD_CONST 0 (无)17 RETURN_VALUE

DUP_TOP 创建一个额外的引用到栈上的值(spam),它存储在 bar 中,然后 baz 被赋予另一个重复的引用,然后将值存储在 eggs 中.

An example of what the title talks about:

#seen in a demo of PyOpenGL
# http://PyOpenGL.sourceforge.net/
size = self.size = self.GetClientSize()

What is this used for? How does it works and when using it?

My idea is this allows to assign the value of the third item to the first and the second... If that's it, we can nest an infinite number of vars.

解决方案

It is a chained assignment. You set both size and self.size to the return value of self.GetClientSize().

You can chain assignments with abandon:

>>> foo = bar = spam = eggs = 'frobnicators'
>>> foo
'frobnicators'
>>> bar, spam, eggs
('frobnicators', 'frobnicators', 'frobnicators')

Note that the expression on the right-hand side only is evaluated once, and it's value is assigned to all the left-hand side variables from left to right.

This can most easily be seen if you decompiled the python bytecode:

>>> import dis
>>> def foo():
...     bar = baz = eggs = 'spam'
... 
>>> dis.dis(foo)
  2           0 LOAD_CONST               1 ('spam')
              3 DUP_TOP             
              4 STORE_FAST               0 (bar)
              7 DUP_TOP             
              8 STORE_FAST               1 (baz)
             11 STORE_FAST               2 (eggs)
             14 LOAD_CONST               0 (None)
             17 RETURN_VALUE        

DUP_TOP creates an extra reference to the value on the stack (spam), which is stored in bar, then baz is given another duplicated reference, then the value is stored in eggs.

这篇关于Python vars 嵌套赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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