在for循环中访问对象属性会导致相同的属性[Python]

时间:2017-04-05 11:25:59

标签: python

使用for循环我试图将字典附加到对象属性:

do = direct_objects[0].point_logs
for direct_object in direct_objects: #Contains two objects
            print ( do is direct_object.point_logs) #Gives true both times
            do = direct_object.point_logs
            print(direct_object.id) #objects are different instances
            dates = generate_dates_interval('2017-01-01', '2017-04-01', 14) #Generates dates with an interval of 14 days for the given period

            for i in range(0, len(dates)-1):

                point_logs, interval_logs, cum_logs = get_point_logs(direct_object, dates[i],
                                                                     dates[i+1]) # gets logs for given period

                if point_logs is not None:
                    direct_object.point_logs.append(point_logs)
                if interval_logs is not None:
                    direct_object.interval_logs.append(interval_logs)
                if cum_logs is not None:
                    direct_object.cum_logs.append(cum_logs)

我想遍历日期并将所有日志附加到DirectObject的point_logs实例。然而,我得到的是,direct_object.point_logs不是两个单独的列表,而是两个直接对象的所有点日志的大列表。

class DirectObject(object):
    def __init__(self, id, created_date, deleted_date, name, type, point_logs = [], interval_logs = [], cum_logs= [],
                 services = None):
        self.id = id
        self.created_date = created_date
        self.deleted_date = deleted_date
        self.name = name
        self.type = type
        self.point_logs = point_logs
        self.interval_logs = interval_logs
        self.cum_logs = cum_logs
        self.services = services

    def __str__(self):
        return str(self.name) + " id: " + str(self.id) + " type: " + str(self.type)
    def __repr__(self):
        return str(self.name) + " id: " + str(self.id) + " type: " + str(self.type)

为什么会这样?

1 个答案:

答案 0 :(得分:1)

由于一切都是Python中的对象,因此用作默认参数的空列表也是一个对象。更重要的是,它是同一个对象!喜欢写a = b = [] 你必须尝试其他食谱,例如这里的食谱。

What is the pythonic way to avoid default parameters that are empty lists?