Using an object inside a class

Gary Herron gherron at digipen.edu
Mon Jan 23 15:23:25 EST 2012


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




More information about the Python-list mailing list