Using an object inside a class

Jonno jonnojohnson at
Mon Jan 23 15:27:27 EST 2012

On Mon, Jan 23, 2012 at 2:09 PM, Ian Kelly <ian.g.kelly at> wrote:

> On Mon, Jan 23, 2012 at 12:44 PM, Jonno <jonnojohnson at> wrote:
> > I have a pretty complicated bit of code that I'm trying to convert to
> more
> > clean OOP.
> Then you probably should not be using globals.

I'm trying to rewrite the whole thing to get rid of my globals.

> > Without getting too heavy into the details I have an object which I am
> > trying to make available inside another class. The reference to the
> object
> > is rather long and convoluted but what I find is that within my class
> > definition this works:
> >
> > class Class1:
> >     def __init__(self):
> >
> >     def method1(self):
> >
> >
> > But this tells me "global name foo is not defined":
> >
> > class Class1:
> >      def __init__(self):
> >  
> Where is foo actually stored?  Is it in fact a global, or is it
> somewhere else?  Please post the actual code.  I suspect that what's
> going on here is that you're assigning foo somewhere inside method1
> and so it is actually a local variable to that method, but there is no
> way to know that for certain from the minimal snippet provided.
> The whole code is complex but here is where I define foo and bar:

class MyApp(wx.App):
    def OnInit(self): = MyFrame(None, -1, 'App Name')
        return True

foo = MyApp(0)

There is nothing inside method1 except the reference.

> > Obviously I want the object to be available throughout the class (I left
> out
> > the self.object = etc for simplicity).
> Do you mean that you want the same object to be available to all
> instances of Class1, or that you just want the object to be available
> to all methods within a single instance (and other instances might
> access other objects)?  In the first case, I would recommend storing
> foo in a class attribute; in the second case, an instance attribute.
> Either way, it would then be accessed simply as "".

Either way would work but the main issue is I can't seem to use foo or or anywhere in __init__ or even before that in the
main class area.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list