[英]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
: 您只需使用参数
arg1
和func
定义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
. 前缀
**
表示函数的所有关键字参数都应分组为一个称为func
的dict
。 So func
is a dict
and func(x)
is an attempt to call the dict
and fails with the error given. 因此,
func
是dict
, func(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.