求助Python类问题
我是Python的初学者,请教大师一个问题.想法是通过类来实现2维坐标(X,Y)列表的处理.代码如下:
import os
import sys
class cls2PtBoundary:
lngX=0
lngY=0
def __init__(self,usrDefault=""):
self.copy_class(usrSourceData=usrDefault)
def is_same(self,other):
if isinstance(other,cls2PtBoundary)==False:
return False
if self.lngX!=other.lngX:
return False
if self.lngY!=other.lngY:
return False
return True
def copy_class(self,usrSourceData=""):
if isinstance(usrSourceData,cls2PtBoundary)==True:
self.lngX=usrSourceData.lngX
self.lngY=usrSourceData.lngY
def set_value(self,lngX=0,lngY=0):
self.lngX=lngX
self.lngY=lngY
def show(self):
return "(" + str(self.lngX) + "," + str(self.lngY) + ")"
class cls2PtBoundaryLST:
lngTotal=0
usr2PtBoundary=[]
def __init__(self,lngTotal=0,usrDefault=""):
self.define(lngTotal=lngTotal,usrDefault=usrDefault)
def define(self,lngTotal=0,blPreserve=False,usrDefault=""):
if lngTotal<=0:
self.lngTotal=0
self.usr2PtBoundary=[]
else:
if blPreserve==True:
if lngTotal>self.lngTotal:
fintIdx=0
while fintIdx<(lngTotal-self.lngTotal):
self.usr2PtBoundary.append(cls2PtBoundary(usrDefault=usrDefault))
fintIdx+=1
else:
self.usr2PtBoundary[lngTotal:]=[]
self.lngTotal=lngTotal
else:
self.lngTotal=lngTotal
fintIdx=0
while fintIdx<lngTotal:
self.usr2PtBoundary.append(cls2PtBoundary(usrDefault=usrDefault))
fintIdx+=1
return self.lngTotal
def get_index(self,usrSourceData):
if self.lngTotal<=0:
return -1
flngIndex=0
while flngIndex<self.lngTotal:
if self.usr2PtBoundary[flngIndex].is_same(usrSourceData)==True:
return flngIndex
flngIndex+=1
return -1
def show(self):
i=0
fsResult=[]
while i<self.lngTotal:
fsResult.append(self.usr2PtBoundary.show())
i+=1
return fsResult
if __name__=='__main__':
x1=cls2PtBoundary()
x2=cls2PtBoundary()
print "x1=" + x1.show()
print "x2=" + x2.show()
x1.set_value(1,1)
x2.set_value(2,2)
print "x1=" + str(x1.show())
print "x2=" + str(x2.show())
y1=cls2PtBoundaryLST(2,x1)
y2=cls2PtBoundaryLST(2,x2)
print "y1=" + str(y1.show())
print "y2=" + str(y2.show())
y2.usr2PtBoundary[1].set_value(3,3)
print "y1=" + str(y1.show())
print "y2=" + str(y2.show())
打印结果出乎我意料:
x1=(0,0)
x2=(0,0)
x1=(1,1)
x2=(2,2)
y1=['(1,1)', '(1,1)']
y2=['(1,1)', '(1,1)']
y1=['(1,1)', '(3,3)']
y2=['(1,1)', '(3,3)']
为什么Y2列表的值和Y1是一样的呢,改变Y2的值,Y1也会改变,这是为什么.好象Y1和Y2是引用的同一个地址.怎么写代码才能实现Y1和Y2的独立呢
多谢大侠们指点
实在是搞不明白了
Python版本用的是2.6.6
多谢了
[ 本帖最后由 shojnhv 于 2013-9-20 15:22 编辑 ]