Python How to make a cross-module function?
- by Evan
I want to be able to call a global function from an imported class, for example
In file 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()
Then when I test in the Python Interpreter
>>> def makenoise():
... return 'bark'
...
>>> from PetStore import AnimalSound
>>> sound = AnimalSound()
>>> sound.makenoise()
'meow'
I get a 'meow' instead of 'bark'. I have tried using the solutions provided in python-how-to-make-a-cross-module-variable with no luck.