【问题标题】:'builtin_function_or_method' object has no attribute '__getitem__' error in pythonpython中的'builtin_function_or_method'对象没有属性'__getitem__'错误
【发布时间】:2019-08-03 23:34:19
【问题描述】:

我正在尝试解释我计划在具有选定目标的机器之间发送的数据,我将把数据发送到该目标以及以下代码应该执行此操作的数据(目标是任意长度的数字,并且具有以“/”开头)我知道整个代码不是很好,而且我可能对几乎所有内容都使用了错误的名称,但我希望在一些帮助下它会起作用

def Interpret(command):
    if(command[0] != "/"):
        return "ERROR"
    o = 1
    targetstr = []
    while(command[o] != " "):
        targetstr.append[command[o]]
        o = o + 1
    try:
        "".join(targetstr)
        target = int(targetstr)
    except:
        return "ERROR"
    data = []
    for i in range(o + 1, len(command)):
        data.append(command[i])
    return [target, "".join(data)]

每次我运行代码时都会收到以下错误消息: targetstr.append[命令[o]] 类型错误:“builtin_function_or_method”对象没有属性“getitem” (显然它应该给我一个包含目标和数据的数组)

【问题讨论】:

  • 由于append 在两次出现的其中一次中被正确调用,因此投票结束是一个错字。
  • "".join(targetstr) 没有做任何有用的事情;它使targetstr 保持不变,同时忽略join 的返回值。你的意思是targetstr = "".join(targetstr)? (另外,targets = [] 将是用于目标 list 的更好名称;它还不是字符串。)

标签: python


【解决方案1】:

list.append() 是一个函数

targetstr.append[command[o]]

应该是

targetstr.append(command[o])

你得到这个特定错误的原因是当你使用方括号语法foo[bar]时,python实际上是在调用foo.__getitem__(bar),而append方法没有__getitem__的属性/方法

【讨论】:

    猜你喜欢
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 2014-05-21
    相关资源
    最近更新 更多