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


Groups > comp.lang.python > #19284

Re: Using an object inside a class

Date 2012-01-23 12:23 -0800
From Gary Herron <gherron@digipen.edu>
Subject Re: Using an object inside a class
References <CAGz2ECYwdnB2ZoTo-DXHhO1_MzdjWeYB+nxeNJ+xivPa8N-tVA@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.4981.1327350608.27778.python-list@python.org> (permalink)

Show all headers | View raw


On 01/23/2012 11:44 AM, Jonno wrote:
> I have a pretty complicated bit of code that I'm trying to convert to 
> more clean OOP.
>
> 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
>
> Obviously I want the object to be available throughout the class (I 
> left out the self.object = etc for simplicity).
>
> Any ideas why I can reference foo inside the method but not in __init__?
>
>

You're not telling us everything.  In fact, with the code you gave us, 
neither method1 nor __init__ will work correctly, because you have not 
defined foo *anywhere*.

Without knowledge of what you are *really* doing, I'll say this:  Both 
method1 and __init__ are methods of Class1, and both have the same rules 
for looking up variables.   If either method binds a value to foo, then 
your code may access it:

class Class1:
      def __init__(self):
            foo = whatever # Local to this method
            foo.bar.object

If the method does not bind it, then Python will look in the class for 
foo.  This could work

class Class1:
      foo = whatever # Available to all instances
      def __init__(self):
            foo.bar.object

If that fails, Python will look in the globals, so this could work:

foo = whatever # Available across the full module
class Class1:
      def __init__(self):
            foo.bar.object

Python goes on one further level when searching for a variable -- that 
being the builtins.







-- 
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Using an object inside a class Gary Herron <gherron@digipen.edu> - 2012-01-23 12:23 -0800

csiph-web