Python在条件下定义函数

时间:2017-02-19 11:58:03

标签: python

这段代码在python中是否正确?

def foo(flag):
    if flag:
        def bar():
           # Somthing
    else:
        def bar():
           # Somthing else
    bar()

foo(True)
foo(False)

如果没有建议的方法来设置某些功能(bar)的行为?条件?

确定真实代码正在关注

# 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

1 个答案:

答案 0 :(得分:1)

这是实现目标的一种合理方式:

def bar1():
    return 'b1'

def bar2():
    return 'b2'

def foo(flag):
    bar = bar2 if flag else bar1
    return bar()

print(foo(False))
print(foo(True))

bar1()之外定义函数bar2()foo()的一个好处是它们可以进行单元测试。