Example 1: python generator cheat sheet download
>>> multiply_by_3 = get_multiplier(3)
>>> multiply_by_3(10)
30
Example 2: python generator cheat sheet download
def get_multiplier(a):
def out(b):
return a * b
return out
Example 3: python generator cheat sheet download
>>> counter = count(10, 2)
>>> next(counter), next(counter), next(counter)
(10, 12, 14)
Example 4: python generator cheat sheet download
from functools import wraps
def debug(func):
@wraps(func)
def out(*args, **kwargs):
print(func.__name__)
return func(*args, **kwargs)
return out
@debug
def add(x, y):
return x + y
Example 5: python generator cheat sheet download
from functools import wraps
def debug(print_result=False):
def decorator(func):
@wraps(func)
def out(*args, **kwargs):
result = func(*args, **kwargs)
print(func.__name__, result if print_result else '')
return result
return out
return decorator
@debug(print_result=True)
def add(x, y):
return x + y
Example 6: python generator cheat sheet download
class <name>:
def __init__(self, a):
self.a = a
def __repr__(self):
class_name = self.__class__.__name__
return f'{class_name}({self.a!r})'
def __str__(self):
return str(self.a)
@classmethod
def get_class_name(cls):
return cls.__name__
Example 7: python generator cheat sheet download
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Employee(Person):
def __init__(self, name, age, staff_num):
super().__init__(name, age)
self.staff_num = staff_num
Example 8: python generator cheat sheet download
>>> permutations('abc', 2)
[('a', 'b'), ('a', 'c'),
('b', 'a'), ('b', 'c'),
('c', 'a'), ('c', 'b')]
Example 9: python generator cheat sheet download
>>> combinations_with_replacement('abc', 2)
[('a', 'a'), ('a', 'b'), ('a', 'c'),
('b', 'b'), ('b', 'c'),
('c', 'c')]
Example 10: python generator cheat sheet download
from itertools import count, repeat, cycle, chain, islice