1.1 python獲取模塊屬性
1.1.1 獲取模塊屬性
描述
python可以通過(guò)點(diǎn)號(hào)或字典,獲取模塊屬性。
已經(jīng)導(dǎo)入的模塊存放在sys.modules字典,通過(guò)getattr獲取模塊屬性。
NO | 獲取屬性 | 描述 |
---|---|---|
1 | M.name | 點(diǎn)號(hào)運(yùn)算,“模塊名”點(diǎn)“屬性名” |
2 | M. dict [‘name’] | 屬性字典,“模塊名”. dict [‘屬性名’] |
3 | sys.modules[‘M’].name | 點(diǎn)號(hào)運(yùn)算,sys.modules[‘模塊名’].屬性名 |
4 | getattr(M,’name’) | getattr(模塊名,’屬性名’) |
注:用as后,通過(guò)字符串方式訪(fǎng)問(wèn)的用“原名”,通過(guò)變量名方式訪(fǎng)問(wèn)的用“別名”。
文件內(nèi)容
E**:**\\documents\\F盤(pán)\\testmatt.py
import os,sys
print("run:{}".format(os.path.abspath(__file__)))
print("__name__:{}".format(__name__))
tyxt='梯閱線(xiàn)條'
示例
# 打開(kāi)cmd 執(zhí)行下面示例
E:\\documents\\F盤(pán)>python
>>> import testmatt as matt
run:E:\\documents\\F盤(pán)\\testmatt.py
__name__:testmatt
# M.name , as 后 , 變量名方式 用別名訪(fǎng)問(wèn)
>>> matt.tyxt
'梯閱線(xiàn)條'
# M.__dict__['name']
>>> matt.__dict__['tyxt']
'梯閱線(xiàn)條'
>>> import sys
# sys.modules['M'].name , as 后 , 字符串方式 用原名訪(fǎng)問(wèn)
>>> sys.modules['testmatt'].tyxt
'梯閱線(xiàn)條'
>>> sys.modules['matt'].tyxt
Traceback (most recent call last):
File "" , line 1, in
KeyError: 'matt'
# getattr(M,'name') , as 后 , 變量名方式 用別名訪(fǎng)問(wèn)
>>> getattr(matt,'tyxt')
'梯閱線(xiàn)條'
>>> getattr(testmatt,'tyxt')
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'testmatt' is not defined
1.2 python字符串導(dǎo)入模塊
python導(dǎo)入模塊時(shí),需提供模塊的變量名,如果導(dǎo)入時(shí)只能獲取模塊字符串形式的名稱(chēng),就會(huì)導(dǎo)入失敗。
1.2.1 描述
NO | 執(zhí)行方式 | 描述 |
---|---|---|
1 | exec(“import M”) | 執(zhí)行引號(hào)內(nèi)導(dǎo)入語(yǔ)句,不返回結(jié)果 |
2 | import (“import M”) | 執(zhí)行引號(hào)內(nèi)導(dǎo)入語(yǔ)句,返回導(dǎo)入模塊 |
1.2.2 exec
示例
# 打開(kāi)cmd 執(zhí)行下面示例
# import 字符串,導(dǎo)入失敗
>>> import 'string'
File "" , line 1
import 'string'
^
SyntaxError: invalid syntax
# 字符串賦值給變量,import 導(dǎo)入失敗
>>> s='string'
>>> import s
Traceback (most recent call last):
File "" , line 1, in
ModuleNotFoundError: No module named 's'
>>> string
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'string' is not defined
>>> impmod='import '+s
# exec()導(dǎo)入成功,直接執(zhí)行,不返回結(jié)果
>>> exec(impmod)
>>> string
'string' from 'D:\\\\python3\\\\lib\\\\string.py'>
>>> s
'string'
1.2.3 import
示例
# 打開(kāi)cmd 執(zhí)行下面示例
>>> s='string'
>>> string
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'string' is not defined
>>> __import__(s)
'string' from 'D:\\\\python3\\\\lib\\\\string.py'>
>>> string
Traceback (most recent call last):
File "" , line 1, in
NameError: name 'string' is not defined
# __import__()返回模塊,需手動(dòng)賦值
>>> string=__import__(s)
>>> string
'string' from 'D:\\\\python3\\\\lib\\\\string.py'>
-
模塊
+關(guān)注
關(guān)注
7文章
2787瀏覽量
50311 -
python
+關(guān)注
關(guān)注
56文章
4827瀏覽量
86668
發(fā)布評(píng)論請(qǐng)先 登錄
2.2 python字符串類(lèi)型
python字符串拼接方式了解
什么是復(fù)制字符串?Python如何復(fù)制字符串
2.2 python字符串類(lèi)型
Python-字符串

評(píng)論