форкнуто от main/python-labs
Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
16 KiB
16 KiB
Отчет по теме 8 Лыкова Елизавета, А-01-23
1. Запуск IDLE, привязка католога, создание файла отчета.
import os,sys,importlib
os.chdir("C:\\Users\\Home\\Desktop\\python-labs\\TEMA8")
os.getcwd()
'C:\\Users\\Home\\Desktop\\python-labs\\TEMA8'
```py
## 2. Создание и использование модулей.
## 2.1 Запуск модуля на выполнение путем его импорта.
```py
perm1 = input('Mod1: Введите значение =')
print('Mod1: Значение perm1 =', perm1)
import Mod1
Mod1:Введите значение = 5
Mod1:Значение perm1= 5
type(Mod1)
<class 'module'>
dir(Mod1)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'perm1']
Mod1.perm1
'5'
import Mod1
importlib.reload(Mod1)
Mod1:Введите значение = 3
Mod1:Значение perm1= 3
<module 'Mod1' from 'C:\\Users\\Home\\Desktop\\python-labs\\TEMA8\\Mod1.py'>
Mod1.perm1
'3'
2.2 Импортированные модули в словаре.
print(sorted(sys.modules.keys()))
['Mod1', '__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']
sys.modules.pop('Mod1')
<module 'Mod1' from 'C:\\Users\\Home\\Desktop\\python-labs\\TEMA8\\Mod1.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', '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']
2.3 Функция exec.
exec(open('Mod1.py').read())
Mod1:Введите значение = 5
Mod1:Значение perm1= 5
exec(open('Mod1.py', encoding='utf-8').read())
Mod1:Введите значение = 5
Mod1:Значение perm1= 5
perm1
'5'
exec(open('Mod1.py', encoding='utf-8').read())
Mod1:Введите значение = 3
Mod1:Значение perm1= 3
perm1
'3'
exec(open('Mod1.py', encoding='utf-8').read())
Mod1:Введите значение = 1
Mod1:Значение perm1= 1
perm1
'1'
2.4 Инструкции from ... import ...
Пример 1
from Mod1 import perm1
Mod1:Введите значение = 5
Mod1:Значение perm1= 5
print(sorted(sys.modules.keys()))
['Mod1', '__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']
perm1
'5'
Пример 2
С помощью текстового редактора создадим ещё один модуль Mod2, содержащий две функции:
def alpha():
print('****ALPHA****')
t=input('Значение t=')
return t
def beta(q):
import math
expi=q*math.pi
return math.exp(expi)
from Mod2 import beta
g = beta(2)
****BETA****
g
535.4916555247646
print(sorted(sys.modules.keys()))
['Mod1', 'Mod2', '__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']
alpha()
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
alpha()
NameError: name 'alpha' is not defined
from Mod2 import alpha as al
al()
****ALPHA****
Значение t=5
'5'
del al,beta
from Mod2 import alpha as al, beta as bt
del al,bt
from Mod2 import*
tt = alpha()
****ALPHA****
Значение t=0.12
uu = beta(float(tt))
****BETA****
uu
1.4578913609506803
3. Создание многомодульных программ.
3.1 Простая многомодулюная программа.
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)
Модуль Mod0
sys.modules.pop('Mod1')
<module 'Mod1' from 'C:\\Users\\Home\\Desktop\\python-labs\\TEMA8\\Mod1.py'>
sys.modules.pop('Mod2')
<module 'Mod2' from 'C:\\Users\\Home\\Desktop\\python-labs\\TEMA8\\Mod2.py'>
import Mod0
Mod1:Введите значение = 3
Mod1:Значение perm1= 3
perm1= 3
****ALPHA****
Значение t=10
tt= 10
****BETA****
qq= 44031505860631.98
Mod0.tt,Mod0.qq,Mod0.Mod1.perm1
('10', 44031505860631.98, '3')
3.2 Еще один пример.
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
Модуль MM1
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)
Модуль MM2
import MM2
print('y=',MM2.vyhod)
Модуль MM0
import MM0
k1,T,k2,Xm,A,F,N=7,2,4,9,5,0.5,1000
y=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1.0183086292055208, 0, 26.39885775889784, -36.65029553691161, -34.19982663883278, 196.29963397615063, -151.6919482160481, -388.32493988337274, 1057.8073200868555, -308.3186572590445, -2798.051869998873, 5004.749701095182, 1362.331454336744, ...]
3.3 Области действия объектов в модулях.
def alpha():
print('****ALPHA****')
t=input('Значение t=')
beta(int(t))
return t
def beta(q):
print('****BETA****')
import math
expi=q*math.pi
return math.exp(expi)
Измененный Mod2.
with a value
from Mod2 import *
alpha()
****ALPHA****
Значение t=2
****BETA****
'2'
Далее:
def alpha():
print('****ALPHA****')
t=input('Значение t=')
return t
def beta(q):
print('****BETA****')
import math
expi=q*math.pi
alpha()
return math.exp(expi)
Еще раз измененный Mod2.
beta(6)
****BETA****
153552935.39544657
Выполнение.
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(t,expi)
Измененный Mod0.
import Mod0
Mod1:Введите значение = 5
Mod1:Значение perm1= 5
perm1= 5
****ALPHA****
Значение t=10
****BETA****
tt= 10
****BETA****
qq= 44031505860631.98
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
import Mod0
File "C:\Users/Home/Desktop/python-labs/TEMA8\Mod0.py", line 10, in <module>
print(t,expi)
NameError: name 't' is not defined. Did you mean: 'tt'?
Выполнение.
import Mod1
print('perm1=',Mod1.perm1)
Mod1.perm1 = str(int(Mod1.perm1)*3)
print('Увеличение perm1 в 3 раза:', Mod1.perm1)
from Mod2 import alpha as al
tt=al()
print('tt=',tt)
from Mod2 import beta
qq=beta(float(tt))
print('qq=',qq)
Измененный Mod0.
import Mod0
perm1= 5
Увеличение perm1 в 3 раза: 15
****ALPHA****
Значение t=10
****BETA****
tt= 10
****BETA****
qq= 44031505860631.98
Выполнение.
import Mod0
perm1= 15
Увеличение perm1 в 3 раза: 45
****ALPHA****
Значение t=10
****BETA****
tt= 10
****BETA****
qq= 44031505860631.98
Mod0.Mod1.perm1=str(int(Mod0.Mod1.perm1)*2)
Mod0.Mod1.perm1
'90'
Mod0.tt = str(int(Mod0.tt)*2)
Mod0.tt
'20'
Mod0.qq=Mod0.qq*2
Mod0.qq
88063011721263.95