Using an object inside a class

Ian Kelly ian.g.kelly at
Mon Jan 23 15:09:38 EST 2012

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.

> 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.

> 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 "".


More information about the Python-list mailing list