Generating instances of class in loop gives TypeError: 'list' object is not callable

Generating instances of class in loop gives TypeError: 'list' object is not callable

我浏览了很多关于这个错误的回复,但是 none 对我的特殊情况很有帮助,而且由于我是 Python 的新手,我很难将提示应用到我的问题。

我在文件 Aheat.py 中有一个 class,它显示为

class Aheat():
    name = ""
    time = 0
    place = 0
    def __init__(self,name,time,place):
        self.name = name
        self.time = time
        self.place = place

还有一个文件 main.py,我想在其中读取 html 文件、提取信息并创建我的 class 的对象列表,以便稍后使用它们。

我的 main.py 的(希望)重要部分是

import urllib2
import re
from Aheat import Aheat

s = read something from url
ssplit = re.split('<p', s)  # now every entry of ssplit contains an event 
                            # and description and all the runners
HeatList = []


for part in ssplit:

    newHeat = Aheat("foo",1,1) # of course this is just an example
    HeatList.append(newHeat)

但这给了我以下错误:

Traceback (most recent call last):
  File "/home/username/Workspace/ECLIPSE/running/main.py", line 22, in <module>
    newHeat = Aheat("foo",1,1)
TypeError: 'list' object is not callable

执行第二次迭代时抛出。

如果我取出循环对象的生成,即

newHeat = Aheat("foo",1,1)
for part in ssplit:

    HeatList.append(newHeat)

我的代码执行没有问题,但这不是我想要的。我也不确定,如果我可以先验地初始化特定数量的实例,因为对象的数量是在循环中估计的。

我正在使用 Eclipse 和 Python 2.7。

正则表达式会咬你的。

<p == <pre> || <progress> || <param> || <p> || (any user created directives on a page.) 按照您评论中的链接阅读为什么我们不应该使用正则表达式解析 html。

谢谢,@MarkR(顺便说一句,我只是在补充你的评论,我同意你的看法)


为什么不把列表放在你的 class 中,或者更好的是用你的 class 扩展列表功能。

class AHeat(list):
    def append(self,name,time,place):
        return super(AHeat,self).append([name,time,place])


# main 
heatList= AHeat()
heatList.append("foo",1,2)
heatList.append("bar",3,4)

print(heatList[0])
print(heatList[1])

> ['foo', 1, 2]
> ['bar', 3, 4]

还有