Using an object inside a class
MRAB
python at mrabarnett.plus.com
Mon Jan 23 15:58:18 EST 2012
On 23/01/2012 20:27, Jonno wrote:
>
>
> On Mon, Jan 23, 2012 at 2:09 PM, Ian Kelly <ian.g.kelly at gmail.com
> <mailto:ian.g.kelly at gmail.com>> wrote:
>
> On Mon, Jan 23, 2012 at 12:44 PM, Jonno <jonnojohnson at gmail.com
> <mailto:jonnojohnson at gmail.com>> 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):
> > foo.bar.object
> >
> > But this tells me "global name foo is not defined":
> >
> > class Class1:
> > def __init__(self):
> > foo.bar.object
>
> 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):
> self.bar = MyFrame(None, -1, 'App Name')
> self.bar.Show(True)
> return True
> foo = MyApp(0)
> app.MainLoop()
>
> There is nothing inside method1 except the foo.bar.object 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 "self.foo".
>
>
> Either way would work but the main issue is I can't seem to use foo or
> foo.bar or foo.bar.object anywhere in __init__ or even before that in
> the main class area.
>
This line:
foo = MyApp(0)
will create a 'MyApp' instance and then bind it to the name 'foo'.
Until that binding occurs, the name 'foo' doesn't exist.
More information about the Python-list
mailing list