【问题标题】:make a parent function return - super return?使父函数返回 - 超级返回?
【发布时间】:2010-10-01 04:52:09
【问题描述】:

我需要在函数的每个后续步骤之后执行检查,因此我想将该步骤定义为函数中的函数。

>>> def gs(a,b):
...   def ry():
...     if a==b:
...       return a
...
...   ry()
...
...   a += 1
...   ry()
...
...   b*=2
...   ry()
... 
>>> gs(1,2) # should return 2
>>> gs(1,1) # should return 1
>>> gs(5,3) # should return 6
>>> gs(2,3) # should return 3

那么我如何让 gs 从 ry 中返回“a”?我曾想过使用 super,但认为这仅适用于类。

谢谢

有点混乱...如果 a==b,我只想返回 a。如果 a!=b,那么我不希望 gs 返回任何东西。

编辑:我现在认为decorators 可能是最好的解决方案。

【问题讨论】:

    标签: python class function return parent


    【解决方案1】:

    你的意思是?

    def gs(a,b):
        def ry():
            if a==b:
                return a
        return ry()
    

    【讨论】:

      【解决方案2】:

      当您在函数中提到“步骤”时,您似乎需要一个生成器:

      def gs(a,b):
        def ry():
          if a==b:
            yield a
        # If a != b, ry does not "generate" any output
        for i in ry():
          yield i
        # Continue doing stuff...
        yield 'some other value'
        # Do more stuff.
        yield 'yet another value'
      

      (生成器现在也可以充当协程,从 Python 2.5 开始,使用 new yield syntax。)

      【讨论】:

      • 这不是我问题的真正答案,但它确实解决了我试图实现的问题:)
      • @All:如果您希望外部函数保持正常功能,并且不必遍历结果,则只能在内部函数中使用 yield。
      【解决方案3】:

      如果 a 和 b 最终相同,这应该允许您继续检查状态并从外部函数返回:

      def gs(a,b):
          class SameEvent(Exception):
              pass
          def ry():
              if a==b:
                  raise SameEvent(a)
          try:
              # Do stuff here, and call ry whenever you want to return if they are the same.
              ry()
      
              # It will now return 3.
              a = b = 3
              ry()
      
          except SameEvent as e:
              return e.args[0]
      

      【讨论】:

      • 有点老套,但我喜欢!非常聪明:)
      【解决方案4】:

      有点混乱...我 如果 a==b 只想返回 a。如果 a!=b,那么我不想让 gs 返回 还有什么。

      然后检查:

      def gs(a,b):
          def ry():
              if a==b:
                  return a
          ret = ry()
          if ret: return ret
          # do other stuff
      

      【讨论】:

        【解决方案5】:

        你明确地返回 ry() 而不是仅仅调用它。

        【讨论】:

          【解决方案6】:

          我遇到了类似的问题,但通过简单地更改调用顺序解决了它。

          def ry ()
              if a==b 
                  gs()
          

          在某些语言(如 javascript)中,您甚至可以将函数作为变量传递给函数:

          function gs(a, b, callback) {
             if (a==b) callback();
          }
          
          gs(a, b, ry);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2010-11-21
            • 2016-10-21
            • 2015-02-13
            • 1970-01-01
            • 1970-01-01
            • 2023-03-23
            • 2021-10-02
            相关资源
            最近更新 更多