简体   繁体   中英

Class Declaration in Python 3.3

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()
...

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM