我想從導入模塊中的類向當前命名空間分配方法(更多一次),我想在「當前」命名空間中執行「分配進程」,但不是來自進口模塊。我怎樣才能做到這一點?將導入模塊中類的方法分配給當前命名空間
該文件是從另一個輸入:
# 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