NameError function not found
Jean-Michel Pichavant
jeanmichel at sequans.com
Mon Jun 1 05:21:28 EDT 2009
Cameron Pulsford wrote:
> Hey everyone, I am extremely stumped on this. I have 2 functions..
>
> def _determinant(m):
> return m[0][0] * m[1][1] - m[1][0] * m[0][1]
>
> def cofactor(self):
> """Returns the cofactor of a matrix."""
> newmatrix = []
> for i, minor in enumerate(self.minors()):
> newmatrix.append(_determinant(minor.matrix) * ((i%2) * -1))
> return newmatrix
>
> And I get the following error when I try to run a.cofactor()...
>
> "NameError: global name '_determinant' is not defined"
>
> When I put the _determinant function nested within the cofactor
> function it works fine. Normally I would do this, but a lot of other
> methods use the _determinant method. They are both in the same class,
> and they are at the same level, they are even in that order so I know
> it should be able to see it. I have a lot of functions that call
> other functions in this class and everything is fine. [Also for the
> picky, I know my cofactor method isn't mathematically correct yet ;-)
> ] Am I missing something obvious here? Also if it helps the rest of
> the code is
> herehttp://github.com/dlocpuwons/pymath/blob/d1997329e4473f8f6b5c7f11635dbd719d4a14fa/matrix.py though
> it is not the latest.
Maybe someone has already answered...
Looks like cofactor is in a class, so I'm assuming _determinant is in
that class as well.
3 solutions:
- declare _determinant outside of the class, making it a private module
function
- declare _determinant as method of the instance : def _determinant(self)
- if you want to keep _determinant as part of your class, it's up to you
but you have to declare it as staticmethod (goolge it for details)
For isntance :
class MyClass
def _determant()m:
...
_determant = staticmethod(_determinant)
def cofactor(self):
...
x = MyClass._determinant(y) # this is how you call static Class
method, but rarely these methods are set private (_ prefix)
Jean-Michel
More information about the Python-list
mailing list