0

I created 'class V' in file 'V.py' with some functions, which I want to keep using in other projects, but when I call any of these functions I get an error that the name is not defined. I tried all solutions that I could find and nothing fixes it. Hope somebody knows what am I doing wrong..

class V(object):

    def magnitude(self):
        a=0
        for i in range(len(self)):
            for j in range(len(self[i])):
                a= a + self[i][j] **2
        return sqrt(a)

Calling a function:

from V import V
A = np.array([[1,2,3],[4,0,6],[7,8,9]])
print magnitude(A)

Error:

NameError: name 'magnitude' is not defined

2 Answers2

0

Refactor your class method to take a parameter, and create an object of class before accessing the method.

from math import sqrt


class V(object):

    def magnitude(self, A):
        a = 0
        for i in range(len(A)):
            for j in range(len(A[i])):
                a = a + A[i][j] ** 2
        return sqrt(a)
import numpy as np
from V import V

v = V()
A = np.array([[1,2,3],[4,0,6],[7,8,9]])
print (v.magnitude(A))

This will work. The reason is you are trying to access class method without creating a class object and passing a parameter inside the method too. self is basically the object on which the method is being called.

sandeshdaundkar
  • 798
  • 6
  • 12
  • Thank you for the response! I ran the code and its giving me some wierd error "TypeError: magnitude() takes exactly 1 argument (2 given)". However if I run it within the original file it works without errors. – Petr Frolkin May 08 '20 at 02:05
  • Did you change your class ? I have tested this code shouldn't break – sandeshdaundkar May 08 '20 at 02:39
-1

You should pass magnitude to class, not to method try:

from V import V
A = np.array([[1,2,3],[4,0,6],[7,8,9]])
m = V(A)
print (V)