I have a class that is essentially supposed to be able to initialize itself and the set internal values based on a line of text (string). This seems to work fine when creating a single instance, however, upon creating a second instance, the line of text fed into the first instance is apparently getting fed into one of the internal variables on the second instance! The init constructor for the class is defined with default values for all relevant parameters which get passed to corresponding internal variables. Specifically, the 'prefixComments' parameter has a default of [] which means that the 'self.PrefixComments' should be set to the same thing (an empty list)... unfortunately, it is apparently getting set to be the line of text that was used to create the previous object (or, at least, that is my best guess).
I am truly puzzled by what is going on here. Any ideas on how to fix it. code and output follows:
code:
import collections
from collections import OrderedDict
import numpy as np
import string
import re
import gc
class AtomEntry:
def __init__(self,atomName="",atomType="",charge=0.0,
comment="",prefixComments=[],
verbose=False):
self.Name=atomName
self.Type=atomType
self.Charge=charge
self.Comment=comment
self.PrefixComments=prefixComments
def from_line_string(self,line):
#returns 1 if an error is encountered, 0 if successful
lineTokens=line.split()
if len(lineTokens)<4:
print("Error: too few entries to construct ATOM record")
return(1)
elif lineTokens[0] != "ATOM":
print("ERROR: atom entries must begin with the keyword 'ATOM'")
return(1)
else:
self.Name=lineTokens[1]
self.Type=lineTokens[2]
self.Charge=float(lineTokens[3])
if len(lineTokens) >=5:
self.Comment=string.replace(
s=' '.join(lineTokens[5:len(lineTokens)]),
old='!',new='')
return(0)
def to_str(self,nameOnly=False):
if nameOnly:
return "%s"%(self.Name)
else:
return repr(self)
def __repr__(self):
outStrs=self.PrefixComments
outStrs.append(
"ATOM %6s %6s %6.3f !%s"%(
self.Name,self.Type,self.Charge,self.Comment))
return ''.join(outStrs)
tempAtom1=AtomEntry()
tempAtom1.from_line_string("ATOM S1 SG2R50 -0.067 ! 93.531")
print tempAtom1
print ""
gc.collect()
tempAtom2=AtomEntry()
tempAtom2.from_line_string("ATOM C1 CG2R53 0.443 ! 83.436")
print tempAtom2
print""
print tempAtom2.Name
print tempAtom2.Type
print tempAtom2.Charge
print tempAtom2.Comment
print tempAtom2.PrefixComments
gc.collect()
output:
ATOM S1 SG2R50 -0.067 !93.531
ATOM S1 SG2R50 -0.067 !93.531ATOM C1 CG2R53 0.443 !83.436
C1
CG2R53
0.443
83.436
['ATOM S1 SG2R50 -0.067 !93.531', 'ATOM C1 CG2R53 0.443 !83.436']