python模块属性及字符串导入模块介绍

1.1 python获取模块属性1.1.1 获取模块属性描述
python可以通过点号或字典,获取模块属性。
已经导入的模块存放在sys.modules字典,通过getattr获取模块属性。
no获取属性描述
1 m.name 点号运算,“模块名”点“属性名”
2 m. dict [‘name’] 属性字典,“模块名”. dict [‘属性名’]
3 sys.modules[‘m’].name 点号运算,sys.modules[‘模块名’].属性名
4 getattr(m,’name’) getattr(模块名,’属性名’)
注:用as后,通过字符串方式访问的用“原名”,通过变量名方式访问的用“别名”。
文件内容
e**:**\\documents\\f盘\\testmatt.py
import os,sysprint(run:{}.format(os.path.abspath(__file__)))print(__name__:{}.format(__name__))tyxt='梯阅线条'示例
# 打开cmd 执行下面示例e:\\documents\\f盘>python>>> import testmatt as mattrun:e:\\documents\\f盘\\testmatt.py__name__:testmatt# m.name , as 后 , 变量名方式 用别名访问>>> matt.tyxt'梯阅线条'# m.__dict__['name']>>> matt.__dict__['tyxt']'梯阅线条'>>> import sys# sys.modules['m'].name , as 后 , 字符串方式 用原名访问>>> sys.modules['testmatt'].tyxt'梯阅线条'>>> sys.modules['matt'].tyxttraceback (most recent call last): file , line 1, in keyerror: 'matt'# getattr(m,'name') , as 后 , 变量名方式 用别名访问>>> getattr(matt,'tyxt')'梯阅线条'>>> getattr(testmatt,'tyxt')traceback (most recent call last): file , line 1, in nameerror: name 'testmatt' is not defined1.2 python字符串导入模块python导入模块时,需提供模块的变量名,如果导入时只能获取模块字符串形式的名称,就会导入失败。
1.2.1 描述no执行方式描述
1 exec(“import m”) 执行引号内导入语句,不返回结果
2 import (“import m”) 执行引号内导入语句,返回导入模块
1.2.2 exec示例
# 打开cmd 执行下面示例# import 字符串,导入失败>>> import 'string' file , line 1 import 'string' ^syntaxerror: invalid syntax# 字符串赋值给变量,import 导入失败>>> s='string'>>> import straceback (most recent call last): file , line 1, in modulenotfounderror: no module named 's'>>> stringtraceback (most recent call last): file , line 1, in nameerror: name 'string' is not defined>>> impmod='import '+s# exec()导入成功,直接执行,不返回结果>>> exec(impmod)>>> string>>> s'string'1.2.3 import示例
# 打开cmd 执行下面示例>>> s='string'>>> stringtraceback (most recent call last): file , line 1, in nameerror: name 'string' is not defined>>> __import__(s)>>> stringtraceback (most recent call last): file , line 1, in nameerror: name 'string' is not defined# __import__()返回模块,需手动赋值>>> string=__import__(s)>>> string

技嘉发布了高端17.3英寸的Aorus 17游戏本,散热效果还有待测试
什么是fpga_fpga是什么
湖北首个智慧能源零碳岛落户襄阳:全岛将部署智慧路灯!
SMT贴片机的加工生产流程是怎样的
Auracast广播音频的应用场景及技术实现
python模块属性及字符串导入模块介绍
承上启下 中国彩电行业2019年增长空间并不大
华为云与中维世纪深度合作,联手打造智慧的云端能力
蓝宝RX5700XTPlus显卡预计在8月30日发布 配备8+6pin供电接口
如何为ADAS处理器提供超过100A的电流?
Redmi K30新技术,有望搭载120Hz显示屏幕
神经协同过滤NCF原理及实战
自动驾驶对动力系统的影响有哪些
盛普国际药物发现网络联盟IDDNU建立基于表型药物发现(PDD)方法
阐述量子信息技术的研究现状与未来
超高效稳定:ERS3041A降压芯片助力电源领域新突破
荣耀Note9什么时候上市?华为荣耀Note9成为华为首款全面屏手机,超大屏+麒麟960加持,价格良心
展望未来,中国移动将全力推动“数字经济”新发展
尚德电力遭纽交所退市警告
数字化施工,成都天府国际机场建设一路高歌