When you declare some variables like this:
class StarCount:
one_stars = 0
two_stars = 0
three_stars = 0
four_stars = 0
five_stars = 0
These variables become class
variables. Class
variables are variables that are shared by all instances of a class. So when you updated genderanalysis.men.straight.five_stars
, it actually updated StarCount.five_stars
and as genderanalysis.women.straight.five_stars
also points to the same variable, it seemed to have updated too.
I think what you are looking for are instance variables
. You can declare them like this:
class StarCount:
def __init__(self):
self.one_stars = 0
self.two_stars = 0
self.three_stars = 0
self.four_stars = 0
self.five_stars = 0
Edit
Why genderanalysis.women.gay.five_stars
is not updated?
What happens is that before you updated any variable of genderanalysis
object, all of the variables were pointing to the variables of StarCount
class. As you can see they have same id:
print(id(StarCount.five_stars)) # prints '94016229389744'
print(id(genderanalysis.men.straight.five_stars)) # prints '94016229389744'
print(id(genderanalysis.women.gay.five_stars)) # prints '94016229389744'
But when you changed genderanalysis.men.straight.five_stars
, the reference/pointer got replaced with your provided value, in this case 100
. You can see difference in their id's:
print(id(StarCount.five_stars)) # prints '94016229389744'
print(id(genderanalysis.men.straight.five_stars)) # prints '94016229391328', see the difference?
So now genderanalysis.men.straight.five_stars
does not point to StarCount.five_stars
, rather it points to OrientationAnalysis.straight.five_stars
. Once again, let's check their id's:
print(id(OrientationAnalysis.straight.five_stars)) # prints '94016229391328'
print(id(genderanalysis.men.straight.five_stars)) # prints '94016229391328', same right?
Now onto your question, at this point genderanalysis.women.gay.five_stars
is still untouched so it points to StarCount.five_stars
and so it still prints 0
. Change StarCount.five_stars
and you can see the change reflecting in genderanalysis.women.gay.five_stars
.
StarCount.five_stars = 101
print(genderanalysis.women.gay.five_stars) # prints `101`