使用Python类和对象进行操作

时间:2018-06-18 19:08:17

标签: python class object vector

我想创建一个Vector类和一个Point类,并在Vector类中有一个能够添加Vector对象和Point对象的函数,但我不明白我是如何操作的类的内部变量。这是我现在的代码:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def AddVector(self, point):
        point2 = Point(0, 0)
        point.x + self.x = point2.x
        point.y + self.y = point2.y
        return point2

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p1 = Point(2,3)
v1 = Vector(4,7)


def main():
    Vector.AddVector(p1,v1)
    print(point2.x, point2.y)

main()

1 个答案:

答案 0 :(得分:1)

首先,不要使用全局变量。这是一个坏习惯。将它们移到main。

然后,主要问题是对实例(p1v1)的调用方法,而不是类(VectorPoint)。第三,使用返回的变量。因此:

def main():
    p1 = Point(2,3)
    v1 = Vector(4,7)
    p2 = p1.AddVector(v1)
    print(p2.x, p2.y)

下一个问题是,这是无效的语法:

point.x + self.x = point2.x

正确的分配方式是另一种方式:

point2.x = point.x + self.x

然后,AddVector上有Vector方法。它应该在Point上,它应该收到Vector作为参数。

所有在一起:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def AddVector(self, v):
        point2 = Point(0, 0)
        point2.x = self.x + v.x
        point2.y = self.y + v.y
        return point2

def main():
    p1 = Point(2,3)
    v1 = Vector(4,7)
    p2 = p1.AddVector(v1)
    print(p2.x, p2.y)

main()

当然,它可能更好,这更先进,但这是为了完整性:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return 'Vector({}, {})'.format(self.x, self.y)


class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, v):
        return Point(self.x + v.x, self.y + v.y)

    def __repr__(self):
        return 'Point({}, {})'.format(self.x, self.y)

def main():
    p1 = Point(2,3)
    v1 = Vector(4,7)
    p2 = p1 + v1
    print(p2)

main()