1

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

3
  • 1
    You reused datecnts to construct the two instances of THING, and while you created a new list the dict inside are the same between the two. Commented Jul 10, 2015 at 2:31
  • Maybe you could print type(item) to make sure that the object is THING and not dict Commented Jul 10, 2015 at 2:48
  • Python doesn't exactly have a way of printing this out so you'll have to make a def __str__(self) if you want to just print out the variable Commented Jul 10, 2015 at 2:49

1 Answer 1

1

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)))
Sign up to request clarification or add additional context in comments.

1 Comment

Accepting the answer is by clicking tick mark on the left side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.