【发布时间】:2018-12-20 01:51:29
【问题描述】:
我有一个类,它本质上应该能够初始化自身并根据一行文本(字符串)设置内部值。 这在创建单个实例时似乎工作正常,但是,在创建第二个实例时,输入第一个实例的文本行显然被输入到第二个实例的一个内部变量中! 类的 init 构造函数定义了所有相关参数的默认值,这些参数传递给相应的内部变量。具体来说,“prefixComments”参数的默认值为 [],这意味着“self.PrefixComments”应该设置为相同的东西(一个空列表)......不幸的是,它显然被设置为文本行用于创建前一个对象(或者,至少,这是我的最佳猜测)。
我真的对这里发生的事情感到困惑。关于如何解决它的任何想法。代码和输出如下:
代码:
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()
输出:
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']
【问题讨论】:
-
请尽量发minimal reproducible example,强调Minimal。
-
@Prune:实际上是两个不同的可变
list问题;一个匹配你的副本,但他们也有第二个问题。我已重新打开以确保不会错过该部分。 -
既然我知道这是核心问题,是否应该将“mutablelist”关键字添加到这篇文章中?
标签: python class python-2.x