python - unittest testcase setup new object -
i'm using pydev in classic eclipse 4.2.2 python2.7. please consider code , result below read.
suppose create object variable of predefined value. now, suppose change value , create new object of same name (i.e., old name points new object). expect old name point new object value not differ predefined value given in class definition. not case. suggestions why?
code:
class example(object): veryimportantdict = {'a': 0} def __init__(self): pass def set_veryimportantnumber(self,key,val): self.veryimportantdict[key] = val if __name__ == '__main__': test = example() print "new object: ", test print "new object's dict: ",test.veryimportantdict test.set_veryimportantnumber('a',5) print "old object's dict: ",test.veryimportantdict test = example() print "new object: ", test print "new object's dict: ",test.veryimportantdict
which returns:
new object: <__main__.example object @ 0x0478c430> new object's dict: {'a': 0} old object's dict: {'a': 5} new object: <__main__.example object @ 0x0478c450> new object's dict: {'a': 5}
you're defining attribute class variable. class vars shared among instances of class. can think of static attribute other languages.
you need define instance variable, in way:
class example(object): def __init__(self): self.veryimportantdict = {'a': 0} def set_veryimportantnumber(self,key,val): self.veryimportantdict[key] = val
also, shouldn't define setter or getter methods until need them. python way change behaviour if find out necessary later on, can avoid bloat of access methods , access attributes directly, so:
class example(object): def __init__(self): self.veryimportantdict = {'a': 0} test.veryimportantdict['a'] = 'foo'
Comments
Post a Comment