Access descendant class's module namespace from superclass

Reid Priedhorsky reid at reidster.net
Mon Jul 11 19:45:20 EDT 2005


Dear group,

I'd have a class defined in one module, which descends from another class
defined in a different module. I'd like the superclass to be able to
access objects defined in the first module (given an instance of the first
class) without importing it. Example of what I'm looking for:

<<<file spam.py>>>

   class Spam(object):
      def fish(self):
         a = self.__module__.Ham()

<<<file eggs.py>>>

   import spam

   class Eggs(spam.Spam):
      pass

   class Ham(object):
      pass

The above doesn't work because __module__ is a string, not a module object: 

   >>> import eggs
   >>> b = eggs.Eggs()
   >>> b.fish()
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
     File "spam.py", line 3, in foo
       a = self.__module__.Ham()
   AttributeError: 'str' object has no attribute 'Ham'

(I suppose I could call __import__(self.__module__), but that seems kind
of awkward.)

Is this possible using Python 2.3? Any better ways to accomplish this?

Thanks very much for any help,

Reid



More information about the Python-list mailing list