Python How to make a cross-module function?

Posted by Evan on Stack Overflow See other posts from Stack Overflow or by Evan
Published on 2010-05-21T05:09:30Z Indexed on 2010/05/21 5:20 UTC
Read the original article Hit count: 290

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about python

Related posts about modules