我想从导入模块中的类向当前名称空间分配方法(一次分配多个),我想不在“当前”名称空间中执行“分配过程”,而是从导入模块执行“分配过程”。我该怎么做?你知道吗
此文件是从另一个文件导入的:
# 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.
谢谢你的帮助。你知道吗
我认为最好是重新构造代码,这样就不必这样做,或许可以这样:
对于主剧本。。。你知道吗
如果真的想更改父命名空间中的内容,那么一种方法可能是:
对于主剧本。。。你知道吗
然而,我想说的是,这给我的印象更像是……“肮脏”。就像,这不是很干净或者很像Python。对于未来/更大的项目,请使用第一种方法。你知道吗
您可以使用
globals()
将变量放入模块的全局名称空间。这够了吗。。。?你知道吗文件:子模块.py你知道吗
主脚本:
输出:
让
assign1
获取要分配的命名空间现在打电话的人会
相关问题 更多 >
编程相关推荐