Scott_1357
Scott_1357

Reputation: 13

Python class instance vs. class variables

I am trying to define a list as an instance variable within a class but it is acting as a class variable.

class THING:
    def __init__(self, name, stuff):
        self.name = name
        self.dict = []
        for item in stuff:
            self.dict.append(item)

    def getname(self):
        return self.name

    def getlist(self):
        return self.dict

    def inc_datecnt(self,date):
        for item in self.dict:
            if item.has_key(date): 
                item[date] += 1



list = []
dates=['July1,2015', 'July2,2015', 'July3,2015']
datecnts = []
for date in dates:
    datecnts.append({date : 0})

list.append(THING('A', datecnts))
list.append(THING('B', datecnts))


for item in list:
    print "\n", item.getname()
    item.inc_datecnt('July1,2015')
    for subitem in item.getlist():
        print subitem

When I execute this I get:

A
{'July1,2015': 1}
{'July2,2015': 0}
{'July3,2015': 0}

B
{'July1,2015': 2}
{'July2,2015': 0}
{'July3,2015': 0}

I seem to be increment a single class dictionary element for July1,2015 when I want (and expect) to be incrementing an instance variable.

Help

Upvotes: 1

Views: 105

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90869

When you are passing datecnts list to your THING object's constructor, you are just passing the reference (and list is mutable and dict are mutable) , hence if you make any changes to the dict for A THING object, it would reflect in B , since B also has the same reference. You should try to do copy.deepcopy of datecnts and send that to A and B separately.

Example -

import copy
list.append(THING('A', copy.deepcopy(datecnts)))
list.append(THING('B', copy.deepcopy(datecnts)))

Upvotes: 1

Related Questions