gpt4 book ai didi

python - Python 3.3 中的类声明

转载 作者:太空宇宙 更新时间:2023-11-04 07:42:24 25 4
gpt4 key购买 nike

我一直在尝试自学如何在 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)

关于python - Python 3.3 中的类声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17002445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com