我想从导入模块中的类向当前命名空间分配方法(更多一次),我想在“当前”命名空间中执行“分配进程”,但不是来自进口模块。我怎样才能做到这一点?将导入模块中类的方法分配给当前命名空间
该文件是从另一个输入:
# File mylib.py
class MyLib():
def hello1(self, text):
print('hello1: %s' % text)
def goodbye1(self, text):
print('goodbye1: %s' % text)
def hello2(self, text):
print('hello2: %s' % text)
def goodbye2(self, text):
print('goodbye2: %s' % text)
def assign1(self):
pass
# This should assign self.hello1() and self.goodbye1()
# to "parent" namespace as hello() and goodbye()
def assign2(self):
pass
# Similar behaviour to self.assign1()
这个文件是“主”之一。
# File myscript.py
import mylib
l = mylib.MyLib()
l.assign1()
# After this I would like to have MyLib.hello1() assigned to hello()
# and MyLib.goodbye1() to goodbye()
hello('hi')
goodbye('see you')
l.assign2()
# After this I would like to have MyLib.hello2() assigned to hello()
# and MyLib.goodbye2() to goodbye()
hello('hi')
goodbye('see you')
到目前为止,我试过globals()
没有成功,结果发现__builtins__
可能会奏效,但似乎不是因为污染__builtins__
命名空间不属于那里内容的正确方法。
我不想要什么:
# In the "current" namespace
hello = l.hello1
goodbye = l.goodbye1
# Instead I want
l.assign1()
# Now hello() and goodbye() are mapped to l.hello1() and l.goodbye1()
# "automatically" - the assign process was done in l.assign1(),
# not here in the "current" namespace.
感谢您的帮助。
感谢大家谁张贴解答。这个解决了我的问题。我修改了一下 - 我将globals()传递给MyLib .__ init __(),所以我不必将它传递给assign1()或assign2() – dwich