Namespace weirdness

Tim Hochberg tim.hochberg at ieee.org
Mon Jul 10 01:27:50 EDT 2000


> > Paul Winkler wrote:
>
> > >class Food:
> > >    def __init__(self, attr1):
> > >        self.attr1 = attr1
> > >    class BodyPart:
> > >        def do_it(self):
> > >            # This next line is a stand-in for what I want...
> > >            print my_parent_namespace.attr1


Just to add to keep tings a bit confusing, let me show a way to do more or
less what you're trying to do. I don't really recomend it, but it's an
entertaining little trick. There are two signifigant changes: first the
class definition is moved up yet another level so that it's defined in the
__init__ function. This is because you're really trying to get at instance
data, not class data. The second change is to specificall add the instance
namespace to the BodyPart class. I also manually added BodyPart to the
instance namespace since otherwise there would be no way to get at it. So
here, for your entertainment is the final version. Enjoy!

class Food:
   def __init__(self, attr1):
       self.attr1 = attr1
       class BodyPart:
           def do_it(self):
               print self._foodInstance.attr1
       BodyPart._foodInstance = self
       self.BodyPart = BodyPart


food = Food("FOO")
bp = food.BodyPart()
bp.do_it()


-tim





More information about the Python-list mailing list