当调用函数时,函数中相同的function_name和parameter_name会产生障碍。谁能解释一下这是怎么回事?

问题描述 投票:0回答:1
#In simple form 

def name(name):
    print(name)

name='arjun'

name(name) #In this line, what's happening?

#Error 'str' object is not callable
python function-call
1个回答
2
投票

函数和其他对象没有单独的命名空间。如果你写

def name1(name2):
    print(name2)

你创建了一个类型为 function,然后将该实例分配给名称为 name1. (A def 语句只是一种非常花哨的赋值语句)。)

参数名是局部变量,属于定义的范围。 功能,而不是范围 其中 函数的定义。这意味着你可以重复使用这个名字,尽管不建议这样做,因为它可能会引起混淆。

   belongs to the scope in which the function is defined
      |
      |    +--- belongs to the scope inside the function
      |    |
      v    v
def name(name):
    print(name)

然而,下面的赋值

name = 'arjun'

与函数定义在同一范围内,因此这使得 name 指代 str 对象而不是 function 它曾经指的对象。

© www.soinside.com 2019 - 2024. All rights reserved.