【问题标题】:Python: Create instance of an object in a loopPython:在循环中创建对象的实例
【发布时间】:2014-06-28 12:25:07
【问题描述】:

此程序从文件中读取数据并为文件每一行的数据创建一个 Tunnel 对象。该计划的细节并不重要。输出将清楚地说明我遇到的问题。

每次我将新隧道(名为 temp)添加到列表时,所有旧隧道(也称为 temp,在 for 循环的先前迭代中创建)都会更改为新隧道 temp。如果这令人困惑,请向下滚动并阅读输出。

class Tunnel: #I am using the data from the file to create tunnel objects
     def __init__ (self,x,y,d):
          self.x=x
          self.y=y
          self.d=d
     def __lt__ (self,other):
          return self.d<other.d  
     def __repr__ (self):
          return "%s %s" % (str(x),str(y))

file = open("ant.in")
n=int(file.readline())
for i in range(0,n): #this loop is irrelevant 
     h,t=(int(s) for s in file.readline().split())
     tList=[]
     mst=[]
for j in range(0,t):
    x,y,d=(int(s) for s in file.readline().split())
    temp = Tunnel(x,y,d) #I create a new tunnel called "temp"
    print(temp) #I print it. It prints as its x and y fields.
    tList.append(temp) #I try and append this new tunnel to my list
    print(tList) #the list prints all the tunnels, but all the tunnels are changed to the most recent one

程序输出

1 2
[1 2]
2 3
[2 3, 2 3]
3 3
[3 3, 3 3, 3 3]
1 4
[1 4, 1 4, 1 4, 1 4]

列表应该打印

[1 2, 3 4, 3 3, 1 4]

【问题讨论】:

    标签: python list loops object naming


    【解决方案1】:

    这是你的 __repr__ -- 使用 self.x & self.y 那里:

    def __repr__ (self):
        return "%s %s" % (self.x, self.y)
    

    所以您的代码实际上可以工作,但对象的打印不正确。它从全局范围打印 xy 而不是实例属性。

    【讨论】:

    • 是的,就是这样!谢谢。
    • 不需要使用str()
    • 是的,我将对此进行编辑 - 只是首先保持与原始内容相同,但最好是正确的。
    【解决方案2】:

    对象是正确的 - 和新对象 - 他们的 repr 但是是错误的: 在__repr__ Tunnel 方法中,您正在打印“x”和“y”变量,而不是 对象的self.xself.y 属性。

    你的代码现在的样子:

     def __repr__ (self):
          return "%s %s" % (str(x),str(y))
    

    让 Python 搜索全局 x 和 y 变量——它们恰好存在,并且对应于用于创建最新对象的值。

    另外 - 如果您使用的是 Python 2.x,请确保您创建的任何类都继承自 object - 否则你会发现前面的意外行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      • 2018-02-19
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      • 2016-09-06
      相关资源
      最近更新 更多