通过修改现有对象来创建新对象

时间:2015-01-25 23:57:20

标签: python object copy

我创建了以下类:

class ball:
    def __init__(self,d=0,weight=0):
        self.d = d
        self.weight = weight

然后我们有一个全局函数返回一个具有修改权重的球,其定义如下:

def modifyWeight(ball, weight):
    ball.weight = weight
    return ball

最后,主要功能,它创建一个给出一系列权重的球列表:

def createBallList(ball, weights):
    ballList = []
    for weight in weights:
        modifyWeight(ball,weight)
        ballList.append(ball)

    return ballList

嗯,正如所解释的那样,weights = [20,25,15]我期望:

ball = ball(2)
ballList = creatBallList(ball,weights)

ballList[0].weight = 20
ballList[1].weight = 25
ballList[2].weight = 15

但结果是:

ballList[0].weight = 15
ballList[1].weight = 15
ballList[2].weight = 15

一直在尝试几件事,但似乎没有任何作品。谢谢!

2 个答案:

答案 0 :(得分:1)

您需要复制该对象,您只需重复将相同的对象添加到列表中,因此当您设置为同一对象设置的权重时,使用copy.deepcopy实际创建一个新对象宾语。

from copy import deepcopy 
cp_b = deepcopy(ball) # new copy of the ball object
modifyWeight(cp_b,weight)

答案 1 :(得分:0)

执行ball.weight = weight时,您不会创建新球。你改变了现有球的重量。执行ballList.append(ball)时,您会将同一个球一遍又一遍地添加到列表中。该名单包含三次相同的球。

如果您想通过循环在每次旅行中创建一个新球,请在每次旅行中通过循环创建一个新球:

def createBallList(weights):
    ballList = []
    for weight in weights:
        newBall = ball(weight=weight)
        ballList.append(newBall)

    return ballList

请注意,您不需要将ball传递给createBallList。如果它所做的一切都是创造新球,而不是使用原始球,它根本不需要原始球。

我不确定d课程中ball的作用是什么,或者为什么将其设置为2,所以我在这里省略了它的部分内容。你可以ball(d=2, weight=weight)创建d设置为2的新球。