【问题标题】:TypeError: 'function' object is not subscriptable - PythonTypeError:“函数”对象不可下标 - Python
【发布时间】:2023-04-02 15:40:01
【问题描述】:

我已尝试使用此代码解决作业:

bank_holiday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
   print(bank_holiday[month])

bank_holiday(int(input("Which month would you like to check out: ")))

但是当我运行它时,我得到了错误:

TypeError: 'function' object is not subscriptable

我不明白这是从哪里来的......

【问题讨论】:

  • 我需要知道我的代码出了什么问题。
  • 这很简单,你有 2 个同名对象,当你说:bank_holiday[month] python 认为你想运行你的函数并得到错误。只需将您的数组重命名为 bank_holidays

标签: python


【解决方案1】:

很简单,你有 2 个同名对象,当你说:bank_holiday[month] Python 认为你想运行你的函数并得到 ERROR。

只需将您的数组重命名为bank_holidays s”!像这样:

bank_holidays= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   if month <1 or month > 12:
       print("Error: Out of range")
       return
   print(bank_holidays[month-1],"holiday(s) in this month ?")

bank_holiday(int(input("Which month would you like to check out: ")))

【讨论】:

    【解决方案2】:

    你可以用这个:

    bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month
    
    def bank_holiday(month):
       month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
       print(bankHoliday[month])
    
    bank_holiday(int(input("Which month would you like to check out: ")))
    

    【讨论】:

    • 您能否包含内联代码跨度,以便代码可读且可验证。
    【解决方案3】:

    您有两个对象都命名为bank_holiday——一个是列表,一个是函数。消除两者的歧义。

    bank_holiday[month] 引发错误,因为 Python 认为 bank_holiday 指的是函数(绑定到名称 bank_holiday 的最后一个对象),而您可能希望它指的是列表。

    【讨论】:

    • 如果您将函数引用命名为类似于变量,也可能会在函数调用时将函数引用作为参数传入。这就是发生在我身上的事。我试图索引参数,然后它是一个函数。
    • 当你在调用函数时错过括号时也会发生这种情况。在我下面的例子中。 def maxProfit2(prices): return ([tomorrow - today for today, tomorrow in zip(prices, prices[1:]) if tomorrow - today > 0]) #calling print(maxProfit2[7,1,5,3,6 ,4])
    猜你喜欢
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2021-12-14
    • 2023-03-20
    • 2015-07-31
    • 2020-02-23
    • 1970-01-01
    相关资源
    最近更新 更多