【问题标题】:Python 3.4: TypeError: 'str' object is not callablePython 3.4:TypeError:“str”对象不可调用
【发布时间】:2014-05-16 02:04:09
【问题描述】:

我正在用 python 制作一个基本游戏,我试图在不同的函数中调用一个全局变量。 这是我收到的错误消息:

File "C:\ARENA\Arena.py", line 154, in <module>
    gamea()
  File "C:\ARENA\Arena.py", line 122, in gamea
    if age1 > age2():
TypeError: 'str' object is not callable

我还是 Python 新手,所以我不确定出了什么问题。这是我正在尝试修复的代码部分

    #character Titles Player1
def char1Title():
    print ("Player 1")
    print()
    global  myName1
    myName1 = input("Whom might you be?")
    print()
    global age1
    age1 = input("What is your age?")

#2 player gameplay code
def gamea():
    attack = input('Enter to start BATTLE!!!!')
**#here's where I try to call "age1" again:**
    if age1 > age2():
        print(myName)
        print("WINS!!")
    elif age2 > age1():
        print(myName2)
        print("WINS!!")

【问题讨论】:

  • 我看到您试图将您的错误编辑到我的答案中。我已经编辑了我的答案以符合要求。我的回答现在对你有用吗?

标签: python function variables global


【解决方案1】:

调用字符串的时候,不要在末尾加上括号,否则python会认为它是一个函数:

>>> string = "hello"
>>> string()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> string
'hello'
>>> 

这是您编辑的代码:

    #character Titles Player1
def char1Title():
    print ("Player 1")
    print()
    global  myName1
    myName1 = input("Whom might you be?")
    print()
    global age1
    age1 = input("What is your age?")

#2 player gameplay code
def gamea():
    attack = input('Enter to start BATTLE!!!!')
    if age1 > age2:
        print(myName)
        print("WINS!!")
    elif age2 > age1:
        print(myName2)
        print("WINS!!")

另外,你不会在任何地方打电话给age2,所以一定要打电话。

【讨论】:

    猜你喜欢
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    相关资源
    最近更新 更多