Skip to main content
 首页 » 编程设计

python之Str 已定义为全局变量

2025年05月04日17artech

我在使用函数时注意到了一些非常奇怪的事情。看起来变量名“str”已经定义为全局变量。看一看:

def Example(x): 
   str = input() 
   return str 
 
print (Example(str)) 
#When typing 'Hello!' Output --> Hello!  

变量 str 在函数 Example 中定义。那么为什么没有 NameError: name 'str' is not defined 呢?

当我调用变量 x 或其他东西时(在本例中为“bar”):

def Example(x): 
   bar = input() 
   return bar 
 
print (Example(bar)) 
#Output: NameError: name 'bar'is not defined 

为什么名称为“str”的变量充当全局变量?

请您参考如下方法:

在 python 中,str() 是字符串构造函数。它用于将对象转换为字符串。

您可以在本地使用它,但它会覆盖对函数的访问。您将无法再使用 str()。

供引用: https://docs.python.org/2/library/functions.html#str

class str(object='')

Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.

出于一般知识目的,如果删除变量,您可以取回构造函数。例如:

test = 1 
str(test) 
>>>'1' 
 
str = 2 
str(test) 
>>>TypeError: 'int' object is not callable 
 
del str 
 
str(test) 
>>>'1'