[英]Class Declaration in Python 3.3
我一直在嘗試着教自己如何在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()
...
您有2種可能性:
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)
導入的工作方式略有不同,您的類是模塊的屬性:
A = Vector2.Vector(-3, -4, 7)
B = Vector2.Vector(6, -2, 2)
或者使用from modulename import objectname
形式:
from Vector2 import Vector
A = Vector(-3, -4, 7)
B = Vector(6, -2, 2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.