namespace question

Steve Holden steve at holdenweb.com
Fri May 18 16:40:06 EDT 2007


T. Crane wrote:
> "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?
> 
Why does it need to? The functions in module "test" will access that 
module's namespace, not that of the calling module.

>> 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.
> 
That should work

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.com        squidoo.com/pythonology
tagged items:         del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------




More information about the Python-list mailing list