'功能' object不是可订阅的错误消息

时间:2017-11-19 17:52:50

标签: python function

我是python的新手,我正在尝试使用库存系统制作基本文本游戏。这一切都很顺利,直到我意识到我需要将整个inv系统作为一个函数,而这就是问题开始的地方。

gloinv = ["apple (food) 5", "health (healthpotion) 10", "sword (weapon) 5"]
hunger = 5
health = 10
fighting = False
enemyLife = 0

def get_num(x):
    return (int(''.join(ele for ele in x if ele.isdigit())))

def inv():
    global gloinv
    global inv
    print(gloinv)
    while True:
        item = input("which item would you like to select?  ")
        select = inv[int(item)-1]
        print("you have selected '", select,"'")
        use = input("type 'use' to use it or 'back' to select another.  ")
        if use == "use":
            if "(food)" in select:
                y = (int(''.join(ele for ele in select if ele.isdigit())))
                print("you have eaten", (select.split(' ', 1)[0] ), "your hunger is now", hunger + y)
                inv.remove(select)
                print(inv)
                gloinv = inv
                break
            elif "(healthpotion)" in select:
                y = (int(''.join(ele for ele in inv[int(item)-1] if ele.isdigit())))
                print("you have drunk", (inv[int(item)-1].split(' ', 1)[0] ), "your health is now", health + y)
                health = health + y
                inv.remove(inv[int(item)-1])
                print(inv)
                gloinv = inv
                break
            elif "weapon" in inv[int(item)-1]:
                if fighting == True:
                    enemyLife - get_num(inv[int(item)-1])
                elif fighting == True:
                    print("you can't use a weapon here")
                break
        elif use == "back":
            print(inv)

inv()
print(gloinv)
print(hunger)
print(health)

我试图适应一些问题,但是当我运行它时,它会出现;

Traceback (most recent call last):
  File "C:\Users\Jenson\Desktop\Python\inv.py", line 47, in <module>
    inv()
  File "C:\Users\Jenson\Desktop\Python\inv.py", line 19, in inv
    select = inv[int(item)-1]
TypeError: 'function' object is not subscriptable
enter code here
>>> 

我已经在这个网站上查看了其他问题,但它们对我来说太混乱了,并且根据不同的代码做了不同的事情。

3 个答案:

答案 0 :(得分:0)

在进行函数调用时使用括号(())而不是括号([])。

答案 1 :(得分:0)

在第19行,您正在执行以下操作:

inv

首先;目前尚不清楚这是什么目的。请仔细检查一下。如果要调用()函数,则需要使用括号int(item)-1调用它,并将方法参数添加到函数声明中。现在,您将某个功能视为列表,并使用from bs4 import BeautifulSoup from urllib.request import urlopen url='https://simple.wikipedia.org/wiki/List_of_U.S._states' web=urlopen(url) source=BeautifulSoup(web, 'html.parser') table=source.find('table', {'class': 'wikitable sortable jquery-tablesorter'}) abbs=table.find_all('b') print(abbs.get_text()) 作为该列表的索引。因此错误。

答案 2 :(得分:0)

感谢您的回答,但我发现该解决方案正在对我自己进行一些测试。我做错了是将函数(inv)标记为与变量(inv)相同的东西我通过命名变量vInv来解决它,因此python不会混淆两者。