namespace question

T. Crane tcrane at REMOVETHISuiuc.edu
Fri May 18 14:29:15 EDT 2007


"Robert Kern" <robert.kern at gmail.com> wrote in message 
news:mailman.7868.1179512371.32031.python-list at python.org...
> T. Crane wrote:
>> Hi,
>>
>> If I define a class like so:
>>
>> class myClass:
>>     import numpy
>>     a = 1
>>     b = 2
>>     c = 3
>>
>>     def myFun(self):
>>         print a,b,c
>>         return numpy.sin(a)
>>
>>
>> I get the error that the global names a,b,c,numpy are not defined. 
>> Fairly
>> straightforward.  But if I am going to be writing several methods that 
>> keep
>> calling the same variables or using the same functions/classes from 
>> numpy,
>> for example, do I have to declare and import those things in each method
>> definition?  Is there a better way of doing this?
>
> Put your imports at the module level. I'm not sure what you intended with 
> a, b,
> c so let's also put them at the top level.

If you put them at the top level, and suppose you saved it all in a file 
called test.py, then when you type

ln [1]: from test import myClass

does it still load a,b,c and numpy into the namespace?

>
> import numpy
> a = 1
> b = 2
> c = 4
>
> class myClass:
>    def myFun(self):
>        print a, b, c
>        return numpy.sin(a)
>
>
> OTOH, if a, b, c were supposed to be attached to the class so they could 
> be
> overridden in subclasses, or be default values for instances, you can 
> leave them
> in the class definition, but access them through "self" or "myClass" 
> directly.

Yeah, they don't need to be accessed anywhere other than within the class 
itself and I won't need to overwrite them, so I'll try just putting them in 
the top level.

thanks,
trevis


>
>
> import numpy
>
> class myClass:
>    a = 1
>    b = 2
>    c = 4
>
>    def myFun(self):
>        print self.a, self.b, myClass.c
>        return numpy.sin(self.a)
>
> -- 
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless 
> enigma
> that is made terrible by our own mad attempt to interpret it as though it 
> had
> an underlying truth."
>  -- Umberto Eco
> 





More information about the Python-list mailing list