這段代碼在Python中是否正確?條件下的Python定義函數
def foo(flag):
if flag:
def bar():
# Somthing
else:
def bar():
# Somthing else
bar()
foo(True)
foo(False)
如果不是什麼建議的方式來設置一些函數(酒吧)的行爲下?條件?
確定真正的代碼如下
# Building replaceFunc based of ignore_case and use_regexp flags
if not ignore_case:
if not use_regexp:
def replaceFunc(string, search, replace):
return string.replace(search, replace)
else:
def replaceFunc(string, search, replace):
pattern = re.compile(search)
return pattern.sub(replace, string)
else:
if not use_regexp:
# There is no standard puthon function for replacing string by ignoring case
def replaceFunc(string, search, replace):
# implementation from http://stackoverflow.com/questions/919056/case-insensitive-replace
return string
else:
def replaceFunc(string, search, replace):
pattern = re.compile(search, re.IGNORECASE)
return pattern.sub(replace, string
你爲什麼不把裏面的吧?爲什麼你需要吧? – BlackBear
爲什麼不把你的if,否則放在'bar'裏 – ZdaR
真實的情況太複雜了。我試圖把簡化的代碼。在實際的例子中,bar被稱爲內部循環。它也需要傳遞給其他函數 – ArmanHunanyan