【问题标题】:What is happening to my lists?我的清单发生了什么?
【发布时间】:2013-03-17 13:53:24
【问题描述】:

我有类点

class Dot:   
  def __init__(self, x, y):
    self.x=x
    self.y=y

我有类集群

class Cluster:
    ic=0
    List=[Dot]
    colour=0
    def __init__(self, Dot):
      self.List[self.ic]=Dot 
      self.ic=self.ic+1
    def includeDot(self, Dot):
      self.List[self.ic]=Dot 
      self.ic=self.ic+1   

其中包括点列表(List)。

我有类 ClusterMaker 在哪里是集群列表(和一些其他程序,但这对于这个问题并不重要)

class ClusterMaker:
    total=0
    i=0
    CList=[Cluster]  
    def addCluster(self,Cluster):
         self.CList.append(Cluster)    

最后,我的表单上有一个按钮开始创建点和簇

def onChoose(self):            
       # ClMaker=ClusterMaker()   
       self.total=self.ent.get().strip() #how many dots we haver
       self.CM=ClusterMaker()
       i=0    
       while (i < int(self.total)):
          dot=Dot(randint(0, 575), randint(0,670))
          clst=Cluster(dot)
          clst.colour= randrange(100, 999, 15)  
          self.CM.addCluster(clst)
          box.showerror('j', str(str(self.CM.CList[i].List[0].x)+str(clst.List[0].x)))
          this box shows us x coord of every dot in our cluster list
          self.canvas.create_oval(clst.List[0].x, clst.List[0].y, clst.List[0].x+10, clst.List[0].y+10, fill=str("#"+str(clst.colour)))
          i=i+1 
       b=0
       while(b<6):
          box.showerror('j', str(self.CM.CList[b].List[0].x))
          and this box shows us x coords too
          b=b+1 

但是我的列表中发生了什么?为什么当我第二次要求显示 x 坐标时,它会为所有集群中的所有点显示相同的 x 坐标?

【问题讨论】:

  • ic(在你的班级)和self.ic不是一回事,请不要将你的变量命名为List

标签: python list class


【解决方案1】:

类属性被实例化一次并在实例之间共享。您必须在__init__ 中创建新列表:

def __init__(self, Dot):
    self.List = [Dot]
    self.List[self.ic]=Dot 
    self.ic=self.ic+1

【讨论】:

  • 谢谢,我希望我能投票给你)当我有更多的声誉时,我会的。我只有 11 个,需要 15 个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多