简体   繁体   English

python中的TypeError,它说字典对象不可调用

[英]TypeError in python which says that dict object is not callable

I'm new to Python. 我是Python的新手。 I am getting the error TypeError:dict object is not callable . 我收到错误TypeError:dict object is not callable I haven't used dictionary anywhere in my code. 我在代码中的任何地方都没有使用字典。

def new_map(*arg1, **func): 
    result = []
    for x in arg1:
        result.append(func(x))
    return result

I tried calling this function as follows: 我尝试按以下方式调用此函数:

new_map([-10], func=abs)

But when I run it, I am getting the above error. 但是,当我运行它时,出现了以上错误。

Seems like you are using arbitrary arguments when they are not required. 似乎在不需要时使用了任意参数。 You can simply define your function with arguments arg1 and func : 您只需使用参数arg1func定义func

def new_map(arg1, func):
    result = []
    for x in arg1:
        result.append(func(x))
    return result

res = new_map([-10], abs)

print(res)

[10]

For detailed guidance on how to use * or ** operators with function arguments see the following posts: 有关如何在函数参数中使用***运算符的详细指导,请参见以下文章:

The ** prefix says that all of the keyword arguments to your function should be grouped into a dict called func . 前缀**表示函数的所有关键字参数都应分组为一个称为funcdict So func is a dict and func(x) is an attempt to call the dict and fails with the error given. 因此, funcdictfunc(x)是尝试调用dict ,但由于给出的错误而失败。

You have used a dictionary by mistake. 已经使用了错误的字典。 When you defined new_map(*arg1, **func) , the func variable gathers the named parameter given during the function call. 定义new_map(*arg1, **func)func变量将收集函数调用期间给定的命名参数。 If func is supposed to be a function, put it as first argument, without * or ** 如果func应该是一个函数,请将其作为第一个参数,不带***

func is a dictionary in your program. func是程序中的dictionary If you want to access value of it then you should use [] not () . 如果要访问它的值,则应使用[] not () Like: 喜欢:

def new_map(*arg1, **func): 
    result = []
    for x in arg1:
        result.append(func[x]) #use [], not ()
    return result

If func is a function to your program then you should write: 如果func是程序的function ,则应编写:

def new_map(*arg1, func): 
    result = []
    for x in arg1:
        result.append(func(x)) #use [], not ()
    return result

Or a simple list comprehension: 或简单的列表理解:

def new_map(arg1, func):
    return [func(i) for i in arg1]

out = new_map([-10], func=abs)
print(out)

Output: 输出:

[10]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM