我想从导入模块中的类到当前命名空间分配方法(一次更多),我想做"分配过程"不在"当前"命名空间,但来自导入的模块。我怎么能这样做?
此文件从另一个文件导入:
# 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()
此文件是" main"之一。
# 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.
感谢您的帮助。
答案 0 :(得分:1)
让assign1
获取您想要指定的名称空间
def assign1(self, namespace):
namespace['hello'] = self.hello1
namespace['goodbye'] = self.goodbye1
现在来电者
import mylib
l = mylib.MyLib()
l.assign1(globals())
答案 1 :(得分:0)
您可以使用globals()
将变量放入模块的全局命名空间。这够了吗?
文件:submodule.py
class Bar(object):
def __init__(self, baz="Hi!"):
self.baz = baz
def foo(self):
print("foo %s" % self.baz)
def assign(self):
globals()["foo"] = self.foo
主脚本:
import submodule
bar = submodule.Bar()
bar2 = submodule.Bar("Bye!")
bar.assign()
submodule.foo()
bar2.assign()
submodule.foo()
输出:
foo Hi!
foo Bye!
答案 2 :(得分:0)
我认为重新构建代码会更好,所以你不必这样做,也许是这样:
# File mylib.py
class MyLib():
#...
def assign1(self):
return hello1, goodbye1
#likewise for assign2
对于主要剧本......
# File myscript.py
import mylib
l = mylib.MyLib()
hello, goodbye = l.assign1()
如果确实想要更改父命名空间中的内容,那么可能有一种方法可以执行此操作:
# File mylib.py
class MyLib():
def __init__(self, funcs): #funcs should be a list
self.funcs = funcs
#...
def assign1(self):
# This should assign self.hello1() and self.goodbye1()
# to "parent" namespace as hello() and goodbye()
self.funcs[0].__code__ = self.hello1.__code__
self.funcs[1].__code__ = self.goodbye1.__code__
#likewise for assign2
对于主要剧本......
# File myscript.py
import mylib
hello = lambda s:s
goodbye = lambda s:s
l = mylib.MyLib([hello, goodbye])
l.assign1()
但是,我想说这对我来说更像......"脏"。就像,这不是非常干净或Pythonic。对于未来/更大的节目,请使用第一种方式。