class Singleton:
__instance = None
# Single call check
def __init__(self):
print('Constructor called!')
@staticmethod
def instance():
if Singleton.__instance is None:
Singleton.__instance = Singleton()
return Singleton.__instance
class CameraSystemManager:
def __init__(self):
self.__observers = list()
def attach(self, observer):
self.__observers.append(observer)
def detach(self, observer):
self.__observers.remove(observer)
def notify(self):
for observer in self.__observers:
observer.take_photo()
class AbstractObserver(ABC):
@abstractmethod
def take_photo(self):
pass
class Camera(AbstractObserver):
def __init__(self, name):
self.name = name
def take_photo(self):
print(f'{self.name}: Photo is done')
camera1 = Camera('Camera 1')
camera2 = Camera('Camera 2')
manager = CameraSystemManager()
manager.attach(camera1)
manager.attach(camera2)
manager.notify()
class AbstractFactory:
@classmethod
def create_form(cls, name):
return cls.Form(name)
@classmethod
def create_button(cls, name):
return cls.Button(name)
class LinuxFactory(AbstractFactory):
class Form:
def __init__(self, name):
self.name = f'LinuxFactory: {name}'
self.button = []
def add_button(self, btn):
self.button.append(btn)
class Button:
def __init__(self, name):
self.name = f'LinuxFactory: {name}'
class WindowsFactory(AbstractFactory):
class Form:
def __init__(self, name):
self.name = f'WindowsFactory: {name}'
self.button = []
def add_button(self, btn):
self.button.append(btn)
class Button:
def __init__(self, name):
self.name = f'WindowsFactory: {name}'
def create_form_with_buttons(factory):
form = factory.create_form('Form 1')
button = factory.create_button('Button 1')
form.add_button(button)
return form
linux_form = create_form_with_buttons(LinuxFactory)
windows_form = create_form_with_buttons(WindowsFactory)
def counter():
cnt = 0
def current():
nonlocal cnt
cnt += 1
print(cnt)
return current
closure_function = counter()
closure_function() # 1
closure_function() # 2
def add(value):
return lambda param: param + value
add_to_100_function = add(100)
a = add_to_100_function(5) # 105
b = add_to_100_function(50)
class Human:
def __init__(self, name):
self.name = name
def speak(self, phrase):
print(f'{self.name} сказал: \'{phrase}\'')
class Doctor(Human):
def __init__(self, name, specialization):
super().__init__(name)
self.specialization = specialization
def diagnose(self):
super().speak(f'Ваш диагноз - ОРВИ')
if __name__ == "__main__":
doctor_alexander = Doctor('Александр', 'Терапевт')
doctor_alexander.diagnose()
class Hobby:
def __init__(self, title):
self.title = title
class Human:
def __init__(self, name, hobby_title):
self.name = name
self.hobby = Hobby(hobby_title)
if __name__ == '__main__':
human = Human('Павел', 'Шахматы')
LENGTH = 7
def create_fib_sequence(length = LENGTH):
lst = [0, 1]
for i in range(1, length-1):
lst.append(lst[i-1] + lst[i])
return lst
res = create_fib_sequence()
def is_palindrome(str):
reversed_str = str[::-1]
return str == reversed_str
for i in range(n-1):
for j in range(n-i-1):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
# Пример 1
def multiply(num):
return lambda x: x + num
multiply_by_10 = multiply(10)
res = multiply_by_10(5)
# Пример 2
filtered_lst = list(filter(lambda x: x % 2 == 0, lst))
filtered_dict = dict(filter(lambda item: 'O' in item[1], dct.items()))
# Пример 3
generated_dict = {item[0]: item[1] * 2 for item in dct.items()}
# Пример 4
mapped_lst = list(map(lambda x: x * 10, lst))
# Простой декоратор
def my_decorator(my_func):
def inner(value):
value *= 2
my_func(value)
return inner
# Декоратор для функции с параметрами
def my_decorator_with_params(my_func):
def inner(*args, **kwargs):
print('Decorator starts...')
my_func(*args, **kwargs)
print('Decorator finishes...')
return inner
@my_decorator
def print_hi():
print('Hi!')
@my_decorator_with_params
def adder(**nums):
print(sum(nums.values()))
# Вызов декорированных функций
print_hi()
adder(a=1, b=2)
import io
with open('1.txt', 'w') as f:
f.write('Hello!')
import io
class MyPersonalException(Exception):
pass
# Example 1
try:
f.write('Hello')
except io.UnsupportedOperation as e:
print('UnsupportedOperation!')
finally:
print('Releasing resources')
f.close()
# Example 2
try:
raise MyPersonalException('This is my personal exception!')
except MyPersonalException as e:
if 'my personal' not in str(e):
raise e
print('My personal exception was caught')
import json
st = 'String'
lst = [1, 2, 3]
dct = {1: 'One', 2: 'Two'}
# Дампим словарь в json и записываем в файл
with open('1.txt', 'w') as f:
json.dump(dct, f, indent=4)
# Формируем json на основе словаря и сохраняем в переменную
my_json = json.dumps(dct, indent=4)
# Парсим строку в словарь или список
my_str = '{"1": "One", "2": "Two"}'
my_json = json.loads(my_str)
my_str = '[1, 2, 3]'
my_json = json.loads(my_str)
def my_func(a, lst=[]):
lst.append(a)
return lst
print(my_func(10))
print(my_func(100))
print(my_func(1000))
[10]
[10, 100]
[10, 100, 1000]
# Иерархия классов
class O: ...
class A(O): ...
class B(O): ...
class C(O): ...
class D(O): ...
class E(O): ...
class F1(A, B, C): ...
class F2(B, D): ...
class F3(C, D, E): ...
class G(F1, F2, F3): ...
# Выведем порядок обхода классов
print(G.mro())
# [<class '__main__.G'>, <class '__main__.F1'>, <class '__main__.A'>, <class '__main__.F2'>, <class '__main__.B'>, <class '__main__.F3'>, <class '__main__.C'>, <class '__main__.D'>, <class '__main__.E'>, <class '__main__.O'>, <class 'object'>]
class X: ...
class Y: ...
class A(X, Y): ...
class B(Y, X): ...
# Создаем мета класс
class CustomMRO(type):
def mro(cls):
return (cls, A, B, X, Y, object)
class F(A, B, metaclass=CustomMRO):
...
print_mro(F) # F -> A -> B -> X -> Y -> object
def division(param):
print('А')
return 1 / param
try:
division(2)
except Exception:
print('В')
else:
print('F')
finally:
print('D')
A
F
D
>>> dir(12) # Хешируемый тип данных
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> hash(12)
12
>>> hash('My string for hash') # Хешируемый тип данных
-8780011054119564709
>>> lst = [1, 2, 3] # Не хешируемый тип данных
>>> hash(lst)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>
# При выполнении следующих двух строк
dсе = {}
dct['my_key'] = 'my_value'
# внутри интерпретатора выполняются следующие действия
internal = []
hash = zlib.crc32(b'my_key')
index = abs(hash) % 1000
internal[index] = ['my_key', 'my_value']