繁体   English   中英

Python 3.3中的类声明

[英]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.

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