我想创建一个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()
答案 0 :(得分:1)
首先,不要使用全局变量。这是一个坏习惯。将它们移到main。
然后,主要问题是对实例(p1
和v1
)的调用方法,而不是类(Vector
和Point
)。第三,使用返回的变量。因此:
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()