TypeError:'long'对象不可调用

时间:2012-06-14 17:24:01

标签: python

我现在已经不知所措了,但我无法弄清楚我的代码有什么问题。 以下是相关部分:

 try:
   outport = record_dict[id][hash_ % len(record_dict[id])]
 except:
   fp.write("Problem-"+str(type(record_dict[id]))+"\n")
   fp.write("Problem-"+str(record_dict[id])+"\n")
   fp.write("Problem-"+str(len(record_dict[id]))+"\n")

这是我得到的错误:

  File "xxxx.py", line 459, in yyyyy
    fp.write("Problem-"+str(len(record_dict[id]))+"\n")
  TypeError: 'long' object is not callable 

fp指向的内部文件:

Problem-<type 'list'>
Problem-[5, 6, 7, 8]

我的代码出了什么问题?我该如何调试呢?

3 个答案:

答案 0 :(得分:7)

您是否在任何地方创建了名为strlen的变量?如果是这样,那就是你的问题。 (很可能是len,因为之前使用过str而没有任何问题。)

Python内置函数不是保留的 - 这意味着您可以自由地将它们重新分配给您想要的任何对象。看起来您已将len分配给一个有意义的长整数,因为len在其他语言中是一个非常合理的变量名称。

你要注意的是小心不要通过创建同名变量来“遮蔽”内置函数。它会产生难以调试的问题。

答案 1 :(得分:1)

作为旁注:裸“除”子句是最糟糕的异常处理方案 - 您只是不知道可能发生什么异常,并且您丢失了存储在异常的回溯中的所有有用的调试信息。 FWIW,sys.exit实际上是通过引发python运行时捕获的SysExit异常来实现的。

如果您处于循环中并希望记录有关当前迭代的异常的信息并继续下一个项目,请确保您没有捕获SysExit并学习使用日志记录模块:

import logging
# this will require some minimal conf somewhere, cf the fine manual
logger = logging.getLogger("my-logger-name")

def myfunction(somesequence):
    for item in somesequence:
        try:
            result = process(item)
        except Exception, e: 
            # in 'recent' python version this will not catch SysExit
            # please refer to the doc for your python version
            # if it's a slightly outdated version, uncomment the
            # following lines:
            # if isinstance(e, SysExit):
            #     raise
            logger.exception("got %s on item %s", e, item)
            continue
        else:
            # ok for this item
            do_something_with(result)

答案 2 :(得分:0)

我在不同的背景下遇到了这个问题:

slope = (nsize*iopsum - (osum)(isum)) / (nsize*oopsum - (osum)*2)

当然我得到它的原因是(osum)(isum)它将osum解释为数字并试图在其上调用不同的数字。所以在它解释之后它看起来像这样:1513(3541),这没有任何意义。

我通过在正确位置(osum)*(isum)

添加*来修复它