What happens in this Python program?

I would like to know what is assigned to line 8.

# Iterators

class Fibs:
    def __init__(self):
        self.a = 0
        self.b = 1
    def next(self):
        self.a, self.b = self.b, self.a+self.b # <--- here
        return self.a
    def __iter__(self):
        return self

fibs = Fibs()

for f in fibs:
    if f > 1000:
        print f
        break

I really don't need the rest of the program. I'm not sure what is attributed to you.

+3
source share
4 answers

This is a para-appointment abbreviated

t = self.a
self.a = self.b
self.b = t+self.b

. , , , , tuple (self.a, self,b) (self.b, self.a+self.b) , , , . , , , , , self.a .

:

.

  • : .
  • , ( ): , , . ( Python 1.5, . , , a, b = "xy", , . )
+7

, :

tmp = self.a
self.a = self.b
self.b = tmp + self.b

:

a' = b
b' = a + b

, , , .

Python . , , - , .

+8

, .

:

a = b
b = a + b

... .

,

1 1 2 3 5 8 13 21 ...

a b , b (b) .

, . , 2 , a , b .

+3

, "" Python. Python, , , , , , . python:

>>> 'a', 'b'

:

('a', 'b')

, .

self.a, self.b = self.b, self.a+self.b

:

(self.a, self.b) = (self.b, self.a+self.b)
  • , self.b self.a + self.b. ( .)
  • , self.a self.b. ( .)
  • , self.a self.b . : .
  • 0 0 .
  • 1 1 .
  • Now that both variables of the left tuple are assigned, delete both tuples. New variables remain with the new values.

So, for example, you can do:

>>> a, b = 1, 2
>>> a, b
(1, 2)
>>> a, b = b, a
>>> a, b
(2, 1)

There are still temporary variables in the hood, but you, the programmer, don't have to deal with them.

0
source

Source: https://habr.com/ru/post/1755140/


All Articles