namespace question

Robert Kern robert.kern at gmail.com
Fri May 18 14:19:07 EDT 2007


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.

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.


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