Multiple Python objects unintentionally sharing reference

时间:2019-02-09 09:35:14

标签: python python-3.x object

Issue

I am declaring a set of companies and dates per company, for some reason whenever I update one of the months for a company, the same month for every company gets updated.

Simplified code snippet

class Company:
    rating = dict()

class Month:
    score = 0
    scoreCount = 0

...

rating.company = "Google"
rating.date = "Nov2018"
rating.score = 5

if rating.company not in companies:
    companies[rating.company] = Company()

if rating.date not in companies[rating.company].rating:
    companies[rating.company].rating[rating.date] = Month()
...

companies[rating.company].rating[rating.date].score += rating.score
companies[rating.company].rating[rating.date].scoreCount += 1

Using python3.5

Case scenario

companies["Google"]["Nov2018"].score = 0
companies["Microsoft"]["Nov2018"].score = 0

Then, when I update the score of one of the two months using the snippet above, the other one is also updated

Expected behavior

Only one of the two Month objects updates after each iteration

Here you can see how both Month objects share the same reference although they're under different companies and declared separately. Sample1 Sample2

0 个答案:

没有答案