Python vars nested assignment

倾然丶 夕夏残阳落幕 提交于 2019-12-14 02:33:08

问题


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.


回答1:


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.




回答2:


When you want to assign the value on RHS to two variables in the same statement..

a = b = 2

Both a and b contains 2..

This can be used when you want to create an alias for your variable, you just assigned value to, because may be you want to use that value in two different ways..




回答3:


It is roughly equivalent to

temp=self.GetClientSize()
size=temp
self.size=temp
del temp

But it executes faster and is generally easier to read than this form. Note that it is not the same as

self.size=self.GetClientSize()
size=self.getClientSize()

which executes self.getClientSize() 2 times, nor the same as

self.size=self.GetClientSize()
size=self.size

observe

class test(object):
    def setter(self, val):
        self._t=val
    def getter(self):
        return 5
    t=property(fget=getter,fset=setter)

a=test()
b=a.t=9
print a.t, b

prints 5 9



来源:https://stackoverflow.com/questions/12655902/python-vars-nested-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!