# Тема 8. Модули и структурирование программы Выполнил: Корнеев М.А. ## 1. Импорт библиотек ``` >>> import os >>> os.chdir("/Users/maksimkorneev/desktop/Лабы/ПОАС/python-labs/Tema8") >>> import sys, importlib ``` ## 2. Создание и использование модулей в среде Python. ### 2.1. Запуск модуля на выполнение путем его импорта. Файл mod1.py содержит команды: ```py perm1 = input('Mod1: Введите значение = ') print('Mod1: Значение perm1 = ', perm1) ``` Вызов файла как импортируемого модуля: ```py >>> import mod1 Mod1: Введите значение = 5 Mod1: Значение perm1 = 5 >>> mod1.perm1 '5' >>> import mod1 >>> import mod1 ``` ```py >>> importlib.reload(mod1) Mod1: Введите значение = 6 Mod1: Значение perm1 = 6 >>> mod1.perm1 '6' ``` ### 2.2. Словарь импортированных модулей ```py >>> print(sorted(sys.modules.keys())) ['__future__', '__main__', '_abc', '_ast', '_bisect', '_bz2', '_codecs', '_collections', '_collections_abc', '_colorize', '_compat_pickle', '_compression', '_datetime', '_frozen_importlib', '_frozen_importlib_external', '_functools', '_heapq', '_imp', '_io', '_lzma', '_opcode', '_opcode_metadata', '_operator', '_pickle', '_pyrepl', '_pyrepl.pager', '_queue', '_random', '_signal', '_sitebuiltins', '_socket', '_sre', '_stat', '_string', '_struct', '_sysconfig', '_thread', '_tkinter', '_tokenize', '_typing', '_warnings', '_weakref', '_weakrefset', '_winapi', '_wmi', 'abc', 'ast', 'bdb', 'binascii', 'bisect', 'builtins', 'bz2', 'codecs', 'collections', 'collections.abc', 'configparser', 'contextlib', 'copyreg', 'datetime', 'dis', 'encodings', 'encodings.aliases', 'encodings.cp1251', 'encodings.utf_8', 'enum', 'errno', 'fnmatch', 'functools', 'genericpath', 'heapq', 'idlelib', 'idlelib.autocomplete', 'idlelib.autocomplete_w', 'idlelib.calltip', 'idlelib.calltip_w', 'idlelib.config', 'idlelib.debugger', 'idlelib.debugger_r', 'idlelib.debugobj', 'idlelib.debugobj_r', 'idlelib.hyperparser', 'idlelib.iomenu', 'idlelib.macosx', 'idlelib.multicall', 'idlelib.pyparse', 'idlelib.rpc', 'idlelib.run', 'idlelib.scrolledlist', 'idlelib.stackviewer', 'idlelib.tooltip', 'idlelib.tree', 'idlelib.util', 'idlelib.window', 'idlelib.zoomheight', 'importlib', 'importlib._abc', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib.machinery', 'importlib.util', 'inspect', 'io', 'ipaddress', 'itertools', 'keyword', 'linecache', 'lzma', 'marshal', 'math', 'mod1', 'nt', 'ntpath', 'opcode', 'operator', 'os', 'os.path', 'pickle', 'pkgutil', 'platform', 'plistlib', 'posixpath', 'pydoc', 'pyexpat', 'pyexpat.errors', 'pyexpat.model', 'queue', 'random', 're', 're._casefix', 're._compiler', 're._constants', 're._parser', 'reprlib', 'select', 'selectors', 'shlex', 'shutil', 'site', 'socket', 'socketserver', 'stat', 'string', 'struct', 'sys', 'sysconfig', 'tempfile', 'textwrap', 'threading', 'time', 'tkinter', 'tkinter.constants', 'token', 'tokenize', 'traceback', 'types', 'typing', 'urllib', 'urllib.parse', 'warnings', 'weakref', 'winreg', 'xml', 'xml.parsers', 'xml.parsers.expat', 'xml.parsers.expat.errors', 'xml.parsers.expat.model', 'zipimport', 'zlib'] >>> sys.modules.pop('mod1') >>> print(sorted(sys.modules.keys())) ['__future__', '__main__', '_abc', '_ast', '_bisect', '_bz2', '_codecs', '_collections', '_collections_abc', '_colorize', '_compat_pickle', '_compression', '_datetime', '_frozen_importlib', '_frozen_importlib_external', '_functools', '_heapq', '_imp', '_io', '_lzma', '_opcode', '_opcode_metadata', '_operator', '_pickle', '_pyrepl', '_pyrepl.pager', '_queue', '_random', '_signal', '_sitebuiltins', '_socket', '_sre', '_stat', '_string', '_struct', '_sysconfig', '_thread', '_tkinter', '_tokenize', '_typing', '_warnings', '_weakref', '_weakrefset', '_winapi', '_wmi', 'abc', 'ast', 'bdb', 'binascii', 'bisect', 'builtins', 'bz2', 'codecs', 'collections', 'collections.abc', 'configparser', 'contextlib', 'copyreg', 'datetime', 'dis', 'encodings', 'encodings.aliases', 'encodings.cp1251', 'encodings.utf_8', 'enum', 'errno', 'fnmatch', 'functools', 'genericpath', 'heapq', 'idlelib', 'idlelib.autocomplete', 'idlelib.autocomplete_w', 'idlelib.calltip', 'idlelib.calltip_w', 'idlelib.config', 'idlelib.debugger', 'idlelib.debugger_r', 'idlelib.debugobj', 'idlelib.debugobj_r', 'idlelib.hyperparser', 'idlelib.iomenu', 'idlelib.macosx', 'idlelib.multicall', 'idlelib.pyparse', 'idlelib.rpc', 'idlelib.run', 'idlelib.scrolledlist', 'idlelib.stackviewer', 'idlelib.tooltip', 'idlelib.tree', 'idlelib.util', 'idlelib.window', 'idlelib.zoomheight', 'importlib', 'importlib._abc', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib.machinery', 'importlib.util', 'inspect', 'io', 'ipaddress', 'itertools', 'keyword', 'linecache', 'lzma', 'marshal', 'math', 'nt', 'ntpath', 'opcode', 'operator', 'os', 'os.path', 'pickle', 'pkgutil', 'platform', 'plistlib', 'posixpath', 'pydoc', 'pyexpat', 'pyexpat.errors', 'pyexpat.model', 'queue', 'random', 're', 're._casefix', 're._compiler', 're._constants', 're._parser', 'reprlib', 'select', 'selectors', 'shlex', 'shutil', 'site', 'socket', 'socketserver', 'stat', 'string', 'struct', 'sys', 'sysconfig', 'tempfile', 'textwrap', 'threading', 'time', 'tkinter', 'tkinter.constants', 'token', 'tokenize', 'traceback', 'types', 'typing', 'urllib', 'urllib.parse', 'warnings', 'weakref', 'winreg', 'xml', 'xml.parsers', 'xml.parsers.expat', 'xml.parsers.expat.errors', 'xml.parsers.expat.model', 'zipimport', 'zlib'] ``` ```py >>> import mod1 Mod1: Введите значение = 9 Mod1: Значение perm1 = 9 >>> mod1.perm1 '9' ``` ### 2.3. Запуск модуля на выполнение с помощью функции exec(). ```py >>> exec(open('mod1.py').read()) Mod1: Введите значение = 7 Mod1: Значение perm1 = 7 >>> perm1 '7' >>> exec(open('mod1.py').read()) Mod1: Введите значение = 99 Mod1: Значение perm1 = 99 >>> perm1 '99' >>> exec(open('mod1.py').read()) Mod1: Введите значение = 40 Mod1: Значение perm1 = 40 >>> perm1 '40' ``` ### 2.4. Использование инструкции from … import … Пример 1. ```py >>> sys.modules.pop('mod1') >>> print(sorted(sys.modules.keys())) ['__future__', '__main__', '_abc', '_ast', '_bisect', '_bz2', '_codecs', '_collections', '_collections_abc', '_colorize', '_compat_pickle', '_compression', '_datetime', '_frozen_importlib', '_frozen_importlib_external', '_functools', '_heapq', '_imp', '_io', '_lzma', '_opcode', '_opcode_metadata', '_operator', '_pickle', '_pyrepl', '_pyrepl.pager', '_queue', '_random', '_signal', '_sitebuiltins', '_socket', '_sre', '_stat', '_string', '_struct', '_sysconfig', '_thread', '_tkinter', '_tokenize', '_typing', '_warnings', '_weakref', '_weakrefset', '_winapi', '_wmi', 'abc', 'ast', 'bdb', 'binascii', 'bisect', 'builtins', 'bz2', 'codecs', 'collections', 'collections.abc', 'configparser', 'contextlib', 'copyreg', 'datetime', 'dis', 'encodings', 'encodings.aliases', 'encodings.cp1251', 'encodings.utf_8', 'enum', 'errno', 'fnmatch', 'functools', 'genericpath', 'heapq', 'idlelib', 'idlelib.autocomplete', 'idlelib.autocomplete_w', 'idlelib.calltip', 'idlelib.calltip_w', 'idlelib.config', 'idlelib.debugger', 'idlelib.debugger_r', 'idlelib.debugobj', 'idlelib.debugobj_r', 'idlelib.hyperparser', 'idlelib.iomenu', 'idlelib.macosx', 'idlelib.multicall', 'idlelib.pyparse', 'idlelib.rpc', 'idlelib.run', 'idlelib.scrolledlist', 'idlelib.stackviewer', 'idlelib.tooltip', 'idlelib.tree', 'idlelib.util', 'idlelib.window', 'idlelib.zoomheight', 'importlib', 'importlib._abc', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib.machinery', 'importlib.util', 'inspect', 'io', 'ipaddress', 'itertools', 'keyword', 'linecache', 'lzma', 'marshal', 'math', 'nt', 'ntpath', 'opcode', 'operator', 'os', 'os.path', 'pickle', 'pkgutil', 'platform', 'plistlib', 'posixpath', 'pydoc', 'pyexpat', 'pyexpat.errors', 'pyexpat.model', 'queue', 'random', 're', 're._casefix', 're._compiler', 're._constants', 're._parser', 'reprlib', 'select', 'selectors', 'shlex', 'shutil', 'site', 'socket', 'socketserver', 'stat', 'string', 'struct', 'sys', 'sysconfig', 'tempfile', 'textwrap', 'threading', 'time', 'tkinter', 'tkinter.constants', 'token', 'tokenize', 'traceback', 'types', 'typing', 'urllib', 'urllib.parse', 'warnings', 'weakref', 'winreg', 'xml', 'xml.parsers', 'xml.parsers.expat', 'xml.parsers.expat.errors', 'xml.parsers.expat.model', 'zipimport', 'zlib'] >>> from mod1 import perm1 Mod1: Введите значение = 89 Mod1: Значение perm1 = 89 >>> print(sorted(sys.modules.keys())) ['__future__', '__main__', '_abc', '_ast', '_bisect', '_bz2', '_codecs', '_collections', '_collections_abc', '_colorize', '_compat_pickle', '_compression', '_datetime', '_frozen_importlib', '_frozen_importlib_external', '_functools', '_heapq', '_imp', '_io', '_lzma', '_opcode', '_opcode_metadata', '_operator', '_pickle', '_pyrepl', '_pyrepl.pager', '_queue', '_random', '_signal', '_sitebuiltins', '_socket', '_sre', '_stat', '_string', '_struct', '_sysconfig', '_thread', '_tkinter', '_tokenize', '_typing', '_warnings', '_weakref', '_weakrefset', '_winapi', '_wmi', 'abc', 'ast', 'bdb', 'binascii', 'bisect', 'builtins', 'bz2', 'codecs', 'collections', 'collections.abc', 'configparser', 'contextlib', 'copyreg', 'datetime', 'dis', 'encodings', 'encodings.aliases', 'encodings.cp1251', 'encodings.utf_8', 'enum', 'errno', 'fnmatch', 'functools', 'genericpath', 'heapq', 'idlelib', 'idlelib.autocomplete', 'idlelib.autocomplete_w', 'idlelib.calltip', 'idlelib.calltip_w', 'idlelib.config', 'idlelib.debugger', 'idlelib.debugger_r', 'idlelib.debugobj', 'idlelib.debugobj_r', 'idlelib.hyperparser', 'idlelib.iomenu', 'idlelib.macosx', 'idlelib.multicall', 'idlelib.pyparse', 'idlelib.rpc', 'idlelib.run', 'idlelib.scrolledlist', 'idlelib.stackviewer', 'idlelib.tooltip', 'idlelib.tree', 'idlelib.util', 'idlelib.window', 'idlelib.zoomheight', 'importlib', 'importlib._abc', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib.machinery', 'importlib.util', 'inspect', 'io', 'ipaddress', 'itertools', 'keyword', 'linecache', 'lzma', 'marshal', 'math', 'mod1', 'nt', 'ntpath', 'opcode', 'operator', 'os', 'os.path', 'pickle', 'pkgutil', 'platform', 'plistlib', 'posixpath', 'pydoc', 'pyexpat', 'pyexpat.errors', 'pyexpat.model', 'queue', 'random', 're', 're._casefix', 're._compiler', 're._constants', 're._parser', 'reprlib', 'select', 'selectors', 'shlex', 'shutil', 'site', 'socket', 'socketserver', 'stat', 'string', 'struct', 'sys', 'sysconfig', 'tempfile', 'textwrap', 'threading', 'time', 'tkinter', 'tkinter.constants', 'token', 'tokenize', 'traceback', 'types', 'typing', 'urllib', 'urllib.parse', 'warnings', 'weakref', 'winreg', 'xml', 'xml.parsers', 'xml.parsers.expat', 'xml.parsers.expat.errors', 'xml.parsers.expat.model', 'zipimport', 'zlib'] >>> perm1 '89' ``` Пример 2. ```py >>> from mod2 import beta >>> g = beta(2) >>> g 535.4916555247646 >>> print(sorted(sys.modules.keys())) ['__future__', '__main__', '_abc', '_ast', '_bisect', '_bz2', '_codecs', '_collections', '_collections_abc', '_colorize', '_compat_pickle', '_compression', '_datetime', '_frozen_importlib', '_frozen_importlib_external', '_functools', '_heapq', '_imp', '_io', '_lzma', '_opcode', '_opcode_metadata', '_operator', '_pickle', '_pyrepl', '_pyrepl.pager', '_queue', '_random', '_signal', '_sitebuiltins', '_socket', '_sre', '_stat', '_string', '_struct', '_sysconfig', '_thread', '_tkinter', '_tokenize', '_typing', '_warnings', '_weakref', '_weakrefset', '_winapi', '_wmi', 'abc', 'ast', 'bdb', 'binascii', 'bisect', 'builtins', 'bz2', 'codecs', 'collections', 'collections.abc', 'configparser', 'contextlib', 'copyreg', 'datetime', 'dis', 'encodings', 'encodings.aliases', 'encodings.cp1251', 'encodings.utf_8', 'enum', 'errno', 'fnmatch', 'functools', 'genericpath', 'heapq', 'idlelib', 'idlelib.autocomplete', 'idlelib.autocomplete_w', 'idlelib.calltip', 'idlelib.calltip_w', 'idlelib.config', 'idlelib.debugger', 'idlelib.debugger_r', 'idlelib.debugobj', 'idlelib.debugobj_r', 'idlelib.hyperparser', 'idlelib.iomenu', 'idlelib.macosx', 'idlelib.multicall', 'idlelib.pyparse', 'idlelib.rpc', 'idlelib.run', 'idlelib.scrolledlist', 'idlelib.stackviewer', 'idlelib.tooltip', 'idlelib.tree', 'idlelib.util', 'idlelib.window', 'idlelib.zoomheight', 'importlib', 'importlib._abc', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib.machinery', 'importlib.util', 'inspect', 'io', 'ipaddress', 'itertools', 'keyword', 'linecache', 'lzma', 'marshal', 'math', 'mod1', 'mod2', 'nt', 'ntpath', 'opcode', 'operator', 'os', 'os.path', 'pickle', 'pkgutil', 'platform', 'plistlib', 'posixpath', 'pydoc', 'pyexpat', 'pyexpat.errors', 'pyexpat.model', 'queue', 'random', 're', 're._casefix', 're._compiler', 're._constants', 're._parser', 'reprlib', 'select', 'selectors', 'shlex', 'shutil', 'site', 'socket', 'socketserver', 'stat', 'string', 'struct', 'sys', 'sysconfig', 'tempfile', 'textwrap', 'threading', 'time', 'tkinter', 'tkinter.constants', 'token', 'tokenize', 'traceback', 'types', 'typing', 'urllib', 'urllib.parse', 'warnings', 'weakref', 'winreg', 'xml', 'xml.parsers', 'xml.parsers.expat', 'xml.parsers.expat.errors', 'xml.parsers.expat.model', 'zipimport', 'zlib'] ``` ```py >>> from mod2 import alpha as al >>> al() ****ALPHA**** Значение t=90 '90' >>> alpha() Traceback (most recent call last): File "", line 1, in NameError: name 'alpha' is not defined ``` ```py >>> del al, beta >>> from mod2 import alpha as al, beta as bt >>> sys.modules.pop('mod2') >>> sys.modules.pop('mod1') >>> from mod2 import * >>> tt = alpha() ****ALPHA**** Значение t=0.13 >>> uu = beta(float(tt)) >>> uu 1.5044194029024176 ``` ## 3. Создание многомодульных программ. ### 3.1. Пример простой многомодульной программы. Модуль 0: ```py import mod1 print('perm1 = ', mod1.perm1) from mod2 import alpha as al tt = al() print('tt = ', tt) from mod2 import beta qq=beta(float(tt)) print('qq = ', qq) ``` ```py >>> import mod0 Mod1: Введите значение = 8 Mod1: Значение perm1 = 8 perm1 = 8 ****ALPHA**** Значение t=2 tt = 2 qq = 535.4916555247646 ``` ```py >>> mod0.tt '2' >>> mod0.qq 535.4916555247646 >>> mod0.mod1.perm1 '8' ``` ### 3.2. Файл mm0.py: ```py import mm2 print('y =', mm2.vyhod) ``` Файл mm1.py: ```py def realdvig(xtt,kk1,TT,yti1,ytin1): #Модель реального двигателя yp = kk1 * xtt #усилитель yti1 = yp + yti1 #Интегратор ytin1 = (yti1+TT*ytin1)/(TT+1) return [yti1, ytin1] def tahogen(xtt,kk2,yti2): #Модель тахогенератора yp = kk2 * xtt #усилитель yti2 = yp + yti2 #интегратор return yti2 def nechus(xtt,gran): if (xtt < gran) and (xtt > (-gran)): ytt = 0 elif xtt >= gran: ytt = xtt - gran elif xtt <= (-gran): ytt = xtt + gran return ytt ``` Файл mm2.py: ```py znach = input('k1,T,k2,Xm,A,F,N=').split(',') k1 = float(znach[0]) T = float(znach[1]) k2 = float(znach[2]) Xm = float(znach[3]) A = float(znach[4]) F = float(znach[5]) N = int(znach[6]) import math vhod = [] for i in range(N): vhod.append(A*math.sin((2*i*math.pi)/F)) import mm1 as mod yi1 = 0; yin1 = 0; yi2 = 0 vyhod=[] for xt in vhod: xt1 = xt - yi2 [yi1,yin1] = mod.realdvig(xt1,k1,T,yi1,yin1) yi2 = mod.tahogen(yin1,k2,yi2) yt = mod.nechus(yin1,Xm) vyhod.append(yt) ``` ```py k1,T,k2,Xm,A,F,N=9,6,4,11,3,0.5,1500 y = [0, 0, ... 0, -70.20177063675057, 0, 257.73311334096866, -677.4095530135962, ... -6.270038281034423e+306, -1.198995988522659e+307] ``` ### 3.3. Области действия объектов в модулях: Обращение в функции alpha к функции beta: ```py def alpha(): print('****ALPHA****') t=input('Значение t=') beta(int(t)) return t def beta(q): import math expi=q*math.pi return math.exp(expi) ``` ```py Mod1: Введите значение = 8 Mod1: Значение perm1 = 8 perm1 = 8 ****ALPHA**** Значение t=4 tt = 4 qq = 286751.31313665316 ``` ```py def alpha(): print('****ALPHA****') t=input('Значение t=') return t def beta(q): import math expi = int(alpha())*math.pi return math.exp(expi) ``` ```py Mod1: Введите значение = 8 Mod1: Значение perm1 = 8 perm1 = 8 ****ALPHA**** Значение t=4 tt = 4 ****ALPHA**** Значение t=4 qq = 286751.31313665316 ``` ```py #Модуль mod0 import mod1 print('perm1 = ', mod1.perm1) from mod2 import alpha as al tt = al() print('tt = ', tt) from mod2 import beta qq=beta(float(tt)) print('qq = ', qq) print(f't = {al.t}, expi = {beta.expi}') Traceback (most recent call last): File "C:\Users\mapon\OneDrive\Рабочий стол\ПО АС\ТЕМА8\mod0.py", line 9, in print(f't = {al.t}, expi = {beta.expi}') AttributeError: 'function' object has no attribute 't' Traceback (most recent call last): File "C:\Users\mapon\OneDrive\Рабочий стол\ПО АС\ТЕМА8\mod0.py", line 10, in print(f't = {al}, expi = {beta.expi}') ^^^^^^^^^ AttributeError: 'function' object has no attribute 'expi' ``` ```py ... print('Умножено:' , int(mod1.perm1) * 3) ... Mod1: Введите значение = 4 Mod1: Значение perm1 = 4 perm1 = 4 Умножено: 12 ``` ```py >>> mod1.perm1 * 2 '55' >>> mod0.tt * 2 '44' >>> mod0.qq * 2 573502.6262733063 ```