根據(jù)字符串的形式去某個對象中操作成員
根據(jù)字符串的形式去一個對象中尋找成員
根據(jù)字符串的形式去一個對象中設(shè)置成員
根據(jù)字符串的形式去一個對象中刪除成員
根據(jù)字符串的形式去一個對象中判斷成員是否存在
通過字符串的形式,導(dǎo)入模塊
根據(jù)用戶輸入的模塊名稱,導(dǎo)入對應(yīng)的模塊并執(zhí)行模塊中的方法
# Python使用的是3.5.1
[root@root ~]# python -V
Python 3.5.1
# commons.py為模塊文件
[root@root ~]# ls
commons.py reflection.py
# commons.py文件內(nèi)容
[root@root ~]# cat commons.py
#!/usr/bin/env python
# 定義了連個函數(shù),f1和f2
def f1():
return "F1"
def f2():
return "F2"
[root@root ~]# cat reflection.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# 輸入模塊的名稱
mod_name = input("請輸入模塊名稱>>> ")
# 查看輸入的內(nèi)容及數(shù)據(jù)類型
print(mod_name, type(mod_name))
# 通過__import__的方式導(dǎo)入模塊,并賦值給dd
dd = __import__(mod_name)
# 執(zhí)行f1()函數(shù)
ret = dd.f1()
# 輸出函數(shù)的返回值
print(ret)
# 執(zhí)行reflection.py
[root@ansheng ~]# python reflection.py
# 輸入模塊名稱
請輸入模塊名稱>>> commons
# 返回輸入的內(nèi)容及數(shù)據(jù)類型
commons <class 'str'>
# 執(zhí)行F1函數(shù)
F1
通過字符串的形式,去模塊中尋找指定函數(shù),并執(zhí)行
用戶輸入模塊名稱和函數(shù)名稱,執(zhí)行指定模塊內(nèi)的函數(shù)or方法
[root@root ~]# cat commons.py
#!/usr/bin/env python
def f1():
return "F1"
def f2():
return "F2"
[root@root ~]# cat reflection.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# 輸入模塊的名稱
mod_name = input("請輸入模塊名稱>>>")
# 輸入函數(shù)or方法的名稱
func_name = input("請輸入函數(shù)名稱>>>")
# 導(dǎo)入模塊
dd = __import__(mod_name)
# 導(dǎo)入模塊中的方法
target_func = getattr(dd, func_name)
# 查看target_func和dd.f1的內(nèi)存地址
print(id(target_func), id(dd.f1))
# 執(zhí)行target_func()函數(shù)
result = target_func()
# 輸出結(jié)果
print(result)
[root@root ~]# python reflection.py
# 輸入模塊名稱commons
請輸入模塊名稱>>>commons
# 輸入函數(shù)名稱f1
請輸入函數(shù)名稱>>>f1
# 返回內(nèi)存地址
139844714989224 139844714989224
# 執(zhí)行的函數(shù)返回結(jié)果
F1
getattr(object, name[, default])
根據(jù)字符串的形式去一個對象中尋找成員
# 自定義模塊的內(nèi)容
[root@root ~]# cat commons.py
#!/usr/bin/env python
Blog_Url = "https://yw666.blog.51cto.com"
def f1():
return "F1"
def f2():
return "F2"
>>> import commons
>>> getattr(commons, "f1")
<function f1 at 0x7fbce5774598>
>>> getattr(commons, "f1f1f1")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'commons' has no attribute 'f1f1f1'
執(zhí)行獲取到的函數(shù)
>>> target_func = getattr(commons, "f1")
>>> target_func
<function f1 at 0x7fbce5774598>
>>> target_func()
'F1'
通過設(shè)置默認值可以避免獲取不到方法時報錯
# 設(shè)置一個默認值為None
>>> target_func = getattr(commons, "f1f1f1", None)
>>> target_func
>>>
通過getattr獲取模塊中的全局變量
>>> import commons
>>> getattr(commons, "Blog_Url", None)
'https://yw666.blog.51cto.com'
setattr(object, name, value)
根據(jù)字符串的形式去一個對象中設(shè)置成員
設(shè)置全局變量
# 獲取commons內(nèi)的Name變量
>>> getattr(commons, "Name", None)
# 在commons模塊中設(shè)置一個全局變量Name,值為Ansheng
>>> setattr(commons, "Name", "YangWen")
# 獲取commons內(nèi)的Name變量
>>> getattr(commons, "Name", None)
'YangWen'
getattr結(jié)合lambda表達式設(shè)置一個函數(shù)
>>> setattr(commons, "as", lambda : print("as"))
>>> getattr(commons, "as")
<function <lambda> at 0x000001FD3E51FD90>
>>> aa = getattr(commons, "as")
>>> aa()
as
delattr(object, name)
根據(jù)字符串的形式去一個對象中刪除成員
>>> getattr(commons, "Name")
'Ansheng'
>>> delattr(commons, "Name")
# 獲取不到就報錯
>>> getattr(commons, "Name")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'commons' has no attribute 'Name'
根據(jù)字符串的形式去一個對象中判斷成員是否存在
# 如果不存在就返回False
>>> hasattr(commons, "Name")
False
>>> setattr(commons, "Name", "YangWen")
# 如果存在就返回True
>>> hasattr(commons, "Name")
True
>>> m = __import__("lib.commons")
>>> m
# 返回的路徑是`lib`
<module 'lib' (namespace)>
>>> m = __import__("lib.commons", fromlist=True)
>>> m
# 返回的路徑是`lib.commons`
<module 'lib.commons' from '/root/lib/commons.py'>
find_index.py
文件內(nèi)容
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
url = input("請輸入url: ")
target_module, target_func = url.split('/')
m = __import__("lib." + target_module, fromlist=True)
if hasattr(m, target_func):
target_func = getattr(m, target_func)
r = target_func()
print(r)
else:
print("404")
目錄結(jié)構(gòu)及文件內(nèi)容
[root@ansheng ~]# tree ./
./
├── find_index.py
└── lib
├── account.py
└── commons.py
1 directory, 3 files
[root@root ~]# cat lib/commons.py
#!/usr/bin/env python
Blog_Url = "yw666.blog.51cto.com"
def f1():
return "F1"
def f2():
return "F2"
[root@root ~]# cat lib/account.py
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
def login():
return "login"
def logout():
return "logout"
執(zhí)行
[root@root ~]# python find_index.py
請輸入url: account/login
login
[root@root ~]# python find_index.py
請輸入url: account/logout
logout
[root@root ~]# python find_index.py
請輸入url: commons/f1
F1
[root@root ~]# python find_index.py
請輸入url: commons/f2
F2
[root@root ~]# python find_index.py
請輸入url: commons/asdasd
404
本文出自 “一盞燭光” 博客,謝絕轉(zhuǎn)載!
更多建議: