如何更改 Python 中一组导入的名称?

How can I change the name of a group of imports in Python?

我想从更改名称的模块中导入所有方法。

例如,而不是

from module import repetitive_methodA as methodA, \
    repetitive_Class1 as Class1, \
    repetitive_instance4 as instance4

我更喜欢

from module import * as *-without-"repetitive_"

这是对这个 clumsy unanswered question 的改写,我还没有找到解决方案或类似的问题。

可以这样做:

import module
import inspect
for (k,v) in inspect.getmembers(module):
    if k.startswith('repetitive_'):
        globals()[k.partition("_")[2]] = v

编辑回复评论"how is this answer intended to be used?"

假设 module 看起来像这样:

# module
def repetitive_A():
    print ("This is repetitive_A")

def repetitive_B():
    print ("This is repetitive_B")

然后在 运行 重命名循环之后,这段代码:

A()
B()

产生这个输出:

This is repetitive_A
This is repetitive_B

我会做什么,创建一个 work-around...

包括你在当前目录下有一个名为some_file.py的文件,它由...

组成
# some_file.py
def rep_a():
    return 1

def rep_b():
    return 2

def rep_c():
    return 3

当您导入某些内容时,您会创建一个 对象,您可以在其上调用方法。这些方法是你的文件的类、变量、函数。

为了得到你想要的,我认为添加一个 新对象 是个好主意,其中包含你想重命名的原始函数。函数 redirect_function() 将一个对象作为第一个参数,并将 迭代 通过该对象的方法(简而言之,它们是您的文件的函数):它会,然后,创建另一个对象,该对象将包含您首先要重命名的函数的指针。

tl;dr : 此函数将创建另一个包含原始函数的对象,但函数的原始名称将 保留。

参见下面的示例。 :)

def redirect_function(file_import, suffixe = 'rep_'):
    #   Lists your functions and method of your file import.
    objects = dir(file_import)

    for index in range(len(objects)):
        #   If it begins with the suffixe, create another object that contains our original function.
        if objects[index][0:len(suffixe)] == suffixe:
            func = eval("file_import.{}".format(objects[index]))
            setattr(file_import, objects[index][len(suffixe):], func)

if __name__ == '__main__':
    import some_file
    redirect_function(some_file)
    print some_file.rep_a(), some_file.rep_b(), some_file.rep_c()
    print some_file.a(), some_file.b(), some_file.c()

这输出...

1 2 3
1 2 3