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

How do you pass in another object of the same type as a method parameter in python?

提问人:Isaiah Blanks 提问时间:11/12/2022 最后编辑:Michael M.Isaiah Blanks 更新时间:11/12/2022 访问量:49

问:

我正在用 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

添加到 时会发生什么变化?adc

Python 对象 方法 按引用 值传递

评论


答:

2赞 Michael M. 11/12/2022 #1

问题在于,您正在 上定义为静态属性。这意味着 的所有实例共享相同的列表。要解决此问题,请创建一个构造函数 () 并在其中定义。喜欢这个:crdPointPointcrd__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]