例如,我希望能够从导入的类中调用全局函数
在文件PetStore.py中
class AnimalSound(object):
def __init__(self):
if 'makenoise' in globals():
self.makenoise = globals()['makenoise']
else:
self.makenoise = lambda: 'meow'
def __str__(self):
return self.makenoise()
Run Code Online (Sandbox Code Playgroud)
然后当我在Python Interpreter中测试时
>>> def makenoise():
... return 'bark'
...
>>> from PetStore import AnimalSound
>>> sound = AnimalSound()
>>> sound.makenoise()
'meow'
Run Code Online (Sandbox Code Playgroud)
我得到'喵'而不是'吠'.我已经尝试过使用python-how-to-make-a-cross-module-variable中提供的解决方案而没有运气.