今天,我發現下面的代碼段的一些怪異的行爲:不一致的行爲在Python 2.7.3與功能相同的名稱和局部變量
if (arg == 0):
# some local variable
format = ""
ret = format + arg
else:
# bultin format function
ret = format(arg, "#x")
print ret
它的作用不同的內部和外部功能。 有了這個代碼:通話
import sys
def foo(arg):
if (arg == 0):
# some local variable
format = ""
ret = format + "0"
else:
# bultin format function
ret = format(arg, "#x")
print ret
arg = int(sys.argv[1])
print "Outside function:"
if (arg == 0):
# some local variable
format = ""
ret = format + "0"
else:
# bultin format function
ret = format(arg, "#x")
print ret
print "Foo call:"
foo(arg)
我獲得以下的輸出:蟒蛇format.py 1
Outside function:
0x1
Foo call:
Traceback (most recent call last):
File "format.py", line 31, in <module>
foo(arg)
File "format.py", line 10, in foo
ret = format(arg, "#x")
的第一個問題是,爲什麼if語句隱藏格式功能下的局部變量在其他語句中使用?
第二個原因是它在行爲函數外面調用時爲什麼會有不同的行爲(現在和預期行爲一樣)?
使用[''' str.format()'''](https://docs.python.org/2/library/stdtypes.html#str.format)而不是['''format()'''](https:// docs.python.org/2/library/string.html#string.Formatter.format)。 – pzp 2015-04-02 13:22:36
無論如何,創建一個與內置函數具有相同名稱的變量是不好的做法;一個人不應該這樣做。但是如果你真的想知道它爲什麼會發生,馬丁的答案是一個非常好的解釋。 – pzp 2015-04-02 13:31:45