I'm trying to learn how to do object oriented coding for scientific computing running a simulation; I'm using using numpy, etc. I've created my first class, WC_unit
, which is located at ./classes/WC_class.py
(a subdirectory). I've created an __init__.py
file (which is empty) in the classes
directory.
The methods for the WC_unit
class require some numpy functions, like exp
When I run the code (in ipython) from the terminal, using
%run WC_class.py
I can generate an instance of the class E1 = WC_unit()
and I can run the associated methods on it, ie E1.update()
I can't really tell if it's working. I wrote some outer code in a script test.py
located at . (above ./classes
) to test the objects I'm generating and I'm trying to import the class by using
from classes.WC_class import WC_unit
Now, when I create an instance E1
of the class and run E1.update()
, I get the error message global name 'exp' is not defined
.
I've tried calling from numpy import *
or also import numpy as np
and changing the function call to np.exp()
and I continue to get the error. Thinking that I had some sort of scoping problem or issues with namespace I've put this same import function at various locations, including in the test.py
file, the top of the class file WC_class.py
, even in the method:
class WC_unit:
def __init__(self): [assign default pars from a dict including r, dt, tau, and Iapp]...
def update(self):
from numpy import *
self.r += self.dt/self.tau * (-self.r + exp(self.Iapp))
I would really like to up my game and figure out how to write my own classes and use them with the awesome computing tools. I guess I'd like to know:
What am I doing wrong (probably a lot, I suspect). I think it's something with how I'm importing my class? but perhaps also scoping in the class itself.
Why does my class lose access to the numpy functions when I
import
it, but not when I run it like a script in the terminal?I guess I also generally don't understand why people are so protective of their namespaces, i.e. why do so many code examples show
import numpy as np
and use all of the functions asnp.exp(x)
, etc. I don't have much of a computer science background so I could benefit a lot from any explanations you could provide- the documentation is kind of cryptic to me.
Python version: 2.7.8 |Anaconda 2.1.0 (x86_64)| (default, Aug 21 2014, 15:21:46) [GCC 4.2.1 (Apple Inc. build 5577)] On Mac OSX 10.6.8