Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #19280 > unrolled thread

Re: Using an object inside a class

Started byIan Kelly <ian.g.kelly@gmail.com>
First post2012-01-23 13:09 -0700
Last post2012-01-23 13:09 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Using an object inside a class Ian Kelly <ian.g.kelly@gmail.com> - 2012-01-23 13:09 -0700

#19280 — Re: Using an object inside a class

FromIan Kelly <ian.g.kelly@gmail.com>
Date2012-01-23 13:09 -0700
SubjectRe: Using an object inside a class
Message-ID<mailman.4976.1327349410.27778.python-list@python.org>
On Mon, Jan 23, 2012 at 12:44 PM, Jonno <jonnojohnson@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.

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

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

Cheers,
Ian

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web