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]