Python的內建函數是否不可用作關鍵字的默認值,還是應該使用其他方式來引用函數?Python內建函數作爲關鍵字參數的默認值?
我想寫這樣的功能:
def isPNGBlock(bytes, blockLen, pngOffset=0, pngErrorLogger=print):
...
try:
r.validate_signature()
width, height, pixels, metadata = r.read(lenient=True)
except png.Error as e:
pngErrorLogger(e)
相反,我只好勉強與無的默認參數作爲一個標誌值這樣做。
def isPNGBlock(bytes, blockLen, pngOffset=0, pngErrorLogger=None):
...
try:
r.validate_signature()
width, height, pixels, metadata = r.read(lenient=True)
except png.Error as e:
if pngErrorLogger is None:
print(e)
else:
pngErrorLogger(e)
或使用包裝函數:
def defaultLogger(str):
print(str)
def isPNGBlock(bytes, blockLen, pngOffset=0, pngErrorLogger=defaultLogger):
...
try:
r.validate_signature()
width, height, pixels, metadata = r.read(lenient=True)
except png.Error as e:
pngErrorLogger(e)