Python adding objects in a for loop
本问题已经有最佳答案,请猛点这里访问。
我有以下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | old_county_code = -1 old_placement_id = -1 placements = [] for row in raw_data: #raw_data is one line from the database retrieved by cursor.fetchall() placement_id = row[1] if placement_id != old_placement_id: placement = Objects.placement() placement.placement_id = placement_id placements.append( placement ) country_code = row[3] if old_county_code != country_code: country = Objects.country() country.country_id = country_code placement.countries.append( country ) creative = Objects.creative( row[2], row[0], row[4], row[5], row[6], row[7] ) country.creatives.append( creative ) old_placement_id = placement_id old_county_code = country_code |
对象放置包含一个国家列表,这些国家本身包含一个创作者列表。所以,当我运行这段代码时,我注意到每个位置都有与列表对象placement.countries中包含的country对象完全相同的数目。事实上,情况并非如此。我想我在代码中做了一些错误,但我不知道是什么。
这是对象代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class placement(object): placement_id = 0 countries = [] class country(object): country_id = 0 creatives = [] class creative(object): creative_id = 0 matching_id = 0 clicks = 0 impressions = 0 ctr = 0.0 rank = 0.0 |
使内部变量基于实例而不是基于类….
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class placement(object): def __init__(self): self.placement_id = 0 self.countries = [] class country(object): def __init__(self): self.country_id = 0 self.creatives = [] class creative(object): def __init__(self) self.creative_id = 0 self.matching_id = 0 self.clicks = 0 self.impressions = 0 self.ctr = 0.0 self.rank = 0.0 |