python - python中如何传入另一个相同类型的对象作为方法参数?

标签 python object methods pass-by-reference pass-by-value

我正在用Python创建一个类来表示一个三维点(我知道有库可以做到这一点,这更多的是类里面的练习)。我希望拥有的一种方法是将一个点的坐标添加到另一个点的坐标。我尝试通过将另一个点作为方法中的参数传递来实现此目的:

class Point:
    crd = [0,0,0]

    def add_vector(self, coord = [], *args) :
        self.crd[0] += coord[0]
        self.crd[1] += coord[1]
        self.crd[2] += coord[2]

    def subtract_point_from_point(self, other) :
        self.crd[0] = self.crd[0] - other.crd[0]
        self.crd[1] = self.crd[1] - other.crd[1]
        self.crd[2] = self.crd[2] - other.crd[2]

我使用以下代码测试了该类,但它的行为与我预期的不同:

a = Point()
b = [2, 2, 4]
a.add_vector(b)

print('Before making c:')
print('a.crd: ' + str(a.crd[0]))
print('a.crd: ' + str(a.crd[1]))
print('a.crd: ' + str(a.crd[2]))

c = Point()
d = [7, 7, 9]
c.add_vector(d)

print('After adding d to c:')
print('a.crd: ' + str(a.crd[0]))
print('a.crd: ' + str(a.crd[1]))
print('a.crd: ' + str(a.crd[2]))

a.subtract_point_from_point(c)

print('After making c: ')
print('a.crd: ' + str(a.crd[0]))
print('a.crd: ' + str(a.crd[1]))
print('a.crd: ' + str(a.crd[2]))

产品:

Before making c:
a.crd: 2
a.crd: 2
a.crd: 4
After adding d to c:
a.crd: 9
a.crd: 9
a.crd: 13
After making c:
a.crd: 0
a.crd: 0
a.crd: 0

d 添加到 c 时,是什么导致 a 发生变化?

最佳答案

问题在于您将 crd 定义为 Point 上的静态属性。这意味着 Point 的所有实例共享相同的列表 crd。要解决此问题,请创建一个构造函数 (__init__()) 并在其中定义 self.crd。像这样:

class Point:
    def __init__(self):
        self.crd = [0, 0, 0]

    def add_vector(self, coord=[], *args):
        self.crd[0] += coord[0]
        self.crd[1] += coord[1]
        self.crd[2] += coord[2]

    def subtract_point_from_point(self, other):
        self.crd[0] = self.crd[0] - other.crd[0]
        self.crd[1] = self.crd[1] - other.crd[1]
        self.crd[2] = self.crd[2] - other.crd[2]

关于python - python中如何传入另一个相同类型的对象作为方法参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74405893/

相关文章:

python - Python OpenCV 中的阴影去除

python - 我如何 'correct' 这个 matplotlib 绘图例程?

python - 为什么 min 和 max 列为序列操作?

ios - 如何将 didSelectViewController 与两个不同的 Controller 一起使用?

java - 两个类和图像不出现

python - 文件中的通用字符串替换

javascript - 比较对象数组

javascript - 使用 'count' 变量添加到对象时,var 'count' 仍然为 0

arrays - 如何在 React 中映射对象数组

java - 如何使用 HashMap 解读单词列表?