1

I have been trying to teach myself how to declare classes in Python, so I'm starting with a simple vector class, adapting an assignment that previously used vectors as just a list and I had to write a module of functions to modify them. Idle is giving me this error:

Traceback (most recent call last):
  File "C:/Users/--------/Documents/Code/Vector/VectorTest2.py", line 7, in <module>
    A = Vector(-3, -4, 7)
NameError: name 'Vector' is not defined

I am really new to Python and don't understand what the documentation is saying, how do I modify these so that I can run the program? The files are in the same directory.

VectorTest2.py

import Vector2

A = Vector(-3, -4, 7)
B = Vector(6, -2, 2)

print(A)
print(B)
...

Vector2.py

class Vector:


    def __init__(self, a, b, c):
        """
        Create new Vector (a, b, c).
        """
        self.L = []
        self.L.append(a)
        self.L.append(b)
        self.L.append(c)
    #end init

    def __str__(self):
        return "[{0}, {1}, {2}]".format(self.L[0], self.L[1], self.L[2])

    def add(self, other):
        """
        Return the vector sum u+v.
        """
        L = []
        for i in range(len(u)):
            L.append(self.L[i] + other.L[i]);
        return Vector(L[0], L[1], L[2])

    # end add()
...

2 Answers 2

4

You have 2 possibilities:

from Vector2 import Vector

A = Vector(-3, -4, 7)
B = Vector(6, -2, 2)

or

import Vector2

A = Vector2.Vector(-3, -4, 7)
B = Vector2.Vector(6, -2, 2)
Sign up to request clarification or add additional context in comments.

Comments

3

Importing works a little different, your class is an attribute of the module:

A = Vector2.Vector(-3, -4, 7)
B = Vector2.Vector(6, -2, 2)

Alternatively use the from modulename import objectname form:

from Vector2 import Vector

A = Vector(-3, -4, 7)
B = Vector(6, -2, 2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.