Паттерны проектирования. Декораторы, итераторы, генераторы... Flashcards

(3 cards)

1
Q

Что такое генератор (generator)?

A
  • Generator-Function: A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.

def simpleGeneratorFun():
yield 1
yield 2
yield 3

for value in simpleGeneratorFun():
print(value)

  • Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop (as shown in the above program).

def simpleGeneratorFun():
yield 1
yield 2
yield 3

x = simpleGeneratorFun()

print(next(x)) # In Python 3, __next__()
print(next(x))
print(next(x))
=========================>
- Генератор — это функция, которая умеет возвращать несколько значений по очереди, не храня в памяти весь набор значений.

  • Генераторы удобны и для создания генераторных выражений — generator expressions.

Особенно это полезно, если нужно сгенерировать много объектов, а память расходовать жалко. Код выглядит так:

gen_exp = (x for x in range(100000))
print(gen_exp)
<generator object <genexpr> at 0x10c4496d0></genexpr>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Что такое итератор (iterator)?

A
  • Iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration.

string = “GFG”
ch_iterator = iter(string)

print(next(ch_iterator))
print(next(ch_iterator))
print(next(ch_iterator))
=============================>
- Iterable is an object, that one can iterate over. It generates an Iterator when passed to iter() method. An iterator is an object, which is used to iterate over an iterable object using the __next__() method. Iterators have the __next__() method, which returns the next item of the object.

next(“GFG”)

Output :
Traceback (most recent call last):
File “/home/1c9622166e9c268c0d67cd9ba2177142.py”, line 2, in <module>
next("GFG")
TypeError: 'str' object is not an iterator</module>

  • Note: Every iterator is also an iterable, but not every iterable is an iterator in Python.
    ===============================>
  • Магический метод __iter__ обозначает, что объект этого класса итерируемый, то есть с ним можно работать в цикле for. Ещё говорят, что __iter__ отдаёт итератор.
  • Любой итератор должен реализовывать магическую функцию __next__, в которой он должен отдавать новые значения. Если вы дошли до конца множества значений, то появляется исключение StopIteration.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Что такое декоратор?

A
  • Декоратор — это паттерн проектирования, предназначенный для расширения функциональности объектов без вмешательства в их код.
  • Переменные, объявленные в объемлющей функции, для вложенной функции находятся в области видимости enclosing scope («объемлющая» или «контекстная» область видимости).
    У вложенных функций есть доступ к переменным в enclosing scope (независимо от уровня вложенности) и к глобальным переменным. Вызвать вложенную функцию можно только из её области видимости.

-Замыкание (closure) — это способность вложенной функции запоминать локальное состояние контекстной области объемлющей функции.

  • The nonlocal keyword is used in nested functions to reference a variable in the parent function.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly