Skip to main content
 首页 » 编程设计

python之Python 3.3 中的类声明

2025年05月04日15shanyou

我一直在尝试自学如何在 Python 中声明类,所以我从一个简单的向量类开始,调整以前使用向量作为列表的赋值,我不得不编写一个函数模块来修改他们。空闲给我这个错误:

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 

我真的是 Python 的新手,不明白文档在说什么,我该如何修改这些以便我可以运行程序?这些文件位于同一目录中。

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

请您参考如下方法:

你有两种可能性:

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

或

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