Python 3.3中的类声明
我一直在尝试教自己如何用Python声明类,所以我从一个简单的向量类开始,修改了一个赋值,以前只使用向量作为列表,我必须编写一个函数模块来修改它们。Idle给了我这个错误:Python 3.3中的类声明,python,python-3.x,Python,Python 3.x,我一直在尝试教自己如何用Python声明类,所以我从一个简单的向量类开始,修改了一个赋值,以前只使用向量作为列表,我必须编写一个函数模块来修改它们。Idle给了我这个错误: Traceback (most recent call last): File "C:/Users/--------/Documents/Code/Vector/VectorTest2.py", line 7, in <module> A = Vector(-3, -4, 7) NameError:
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
Vector2.py
import Vector2
A = Vector(-3, -4, 7)
B = Vector(6, -2, 2)
print(A)
print(B)
...
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()
...
导入的工作原理稍有不同,您的类是模块的一个属性:
A = Vector2.Vector(-3, -4, 7)
B = Vector2.Vector(6, -2, 2)
或者使用modulename导入对象名的表单:
from Vector2 import Vector
A = Vector(-3, -4, 7)
B = Vector(6, -2, 2)
导入的工作原理稍有不同,您的类是模块的一个属性:
A = Vector2.Vector(-3, -4, 7)
B = Vector2.Vector(6, -2, 2)
或者使用modulename导入对象名的表单:
from Vector2 import Vector
A = Vector(-3, -4, 7)
B = Vector(6, -2, 2)
您有两种可能:
from Vector2 import Vector
A = Vector(-3, -4, 7)
B = Vector(6, -2, 2)
或
您有两种可能:
from Vector2 import Vector
A = Vector(-3, -4, 7)
B = Vector(6, -2, 2)
或