Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法修复Python错误AttributeError:';int';对象没有属性';获取';_Python - Fatal编程技术网

无法修复Python错误AttributeError:';int';对象没有属性';获取';

无法修复Python错误AttributeError:';int';对象没有属性';获取';,python,Python,我的源代码 def display_inventory(inventory): print("Itme list") item_total = 0 for k,v in inventory.items(): print(str(k) + str(v)) item_total = item_total + v.get(k,0) print("The total number of items:"

我的源代码

def display_inventory(inventory):
    print("Itme list")
    item_total = 0
    for k,v in inventory.items():
        print(str(k) + str(v))
        item_total = item_total + v.get(k,0)
    print("The total number of items:" + str(item_total))

stuff = {'rope':1, 'torch':6, 'coin':42, 'Shuriken':1, 'arrow':12}
display_inventory(stuff)
错误消息

AttributeError: 'int' object has no attribute 'get'
你能告诉我如何修复这个错误吗?如果你能解释一下为什么这不起作用,我将不胜感激


提前谢谢你

你为什么不写以下内容呢:

def显示_库存(库存):
打印(“Itme列表”)
项目总数=0
对于inventory.items()中的k、v:
打印(str(k)+str(v))

item_total=item_total+v#在字典中,
v
是一个整数。字典中的所有内容都在
inventory.items()
中提取。您正在尝试从整数中提取某些内容。因此,它显示了一个错误。解决方案是简单地更改为
v

def display_inventory(inventory: dict):
    print("Item list")
    item_total = 0
    for k,v in inventory.items():
        print(str(k) + str(v))
        item_total = item_total + v #=== Here
    print("The total number of items:" + str(item_total))

stuff = {'rope':1, 'torch':6, 'coin':42, 'Shuriken':1, 'arrow':12}
display_inventory(stuff)
以及输出:

rope1
torch6
coin42
Shuriken1
arrow12
The total number of items:62
  • 应在字典上调用
    get
    (即
    inventory
  • 无需调用
    get
    ,因为循环中
    v=inventory[k]
  • 如果
    k
    不存在,则不需要设置默认值,因为inventory.items()中的k,v的
    仅在现有项之间循环

  • 该错误与
    v.get(k,0)
    一致。
    .get()
    函数的语法为

    .get(,
    并在字典中输出一个值

    而通常的
    []
    方法会在密钥不存在时抛出错误

    在inventory.items()中迭代k,v的键值对时,特定于您的代码:
    ,该键保证存在

    由于您已经在迭代字典中的值,因此您可以简单地使用

    项目总数+=v

    关于
    print(str(k)+str(v))
    的其他反馈,您可以尝试以下方法:

  • 使用
    +
    符号
    打印(str(k)+''+str(v))
    只允许
    字符串
  • 或者使用
    表示法
    打印(k,v)
    ,它允许混合使用
    字符串
    列表
  • 打印中使用
    符号(“项目总数:”,项目总数)
  • 输出

    rope 1
    torch 6
    coin 42
    Shuriken 1
    arrow 12
    The total number of items: 62
    
    顺便说一下,
    打印(“Itme列表”)
    中有一个打字错误


    干杯!

    int没有get属性是有道理的。您认为get在这里应该做什么呢?
    对于dict.items()中的k,v
    。因此
    v
    接受以
    k
    为键的元素的值。显然,此元素是一个int,因此您不能将get方法应用于整数。get可以应用于dict,例如库存。因此,两个正确的行是
    item\u total+v
    item\u total+inventory。get(k)
    Welcome@Eric。我不明白为什么这个问题是-2,还需要一个人来帮助中和反对票