如何在Python中更改一组导入的名称? [英] How can I change the name of a group of imports in Python?
本文介绍了如何在Python中更改一组导入的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从名称更改的模块中导入所有方法。
I would like to import all methods from a module with altered names.
例如,而不是
from module import repetitive_methodA as methodA, \
repetitive_Class1 as Class1, \
repetitive_instance4 as instance4
我更喜欢
from module import * as *-without-"repetitive_"
这是对此笨拙未回答的问题,我找不到解决方案或类似的问题。
this is a rephrasing of this clumsy unanswered question, I have not been able to find a solution or similar questions yet.
推荐答案
你可以这样做:
import module
import inspect
for (k,v) in inspect.getmembers(module):
if k.startswith('repetitive_'):
globals()[k.partition("_")[2]] = v
编辑以回应评论这个答案打算如何使用?
假设模块
如下所示:
# module
def repetitive_A():
print ("This is repetitive_A")
def repetitive_B():
print ("This is repetitive_B")
然后在运行重命名循环后,此代码:
Then after running the rename loop, this code:
A()
B()
产生这个输出:
This is repetitive_A
This is repetitive_B
这篇关于如何在Python中更改一组导入的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文