让父函数返回 - 超级回报?

时间:2009-01-13 17:59:41

标签: python class function return parent

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

>>> 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,但认为这只适用于课程。

由于

有点混乱......我只想要返回一个if = = b。如果a!= b,那么我不希望gs返回任何内容。

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

6 个答案:

答案 0 :(得分:10)

你的意思是?

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

答案 1 :(得分:4)

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

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。)

答案 2 :(得分:3)

  

有点混乱......我   只想返回一个if === b。如果   a!= b,然后我不希望gs返回   什么都没有。

然后检查:

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

答案 3 :(得分:2)

如果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 :(得分:1)

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

答案 5 :(得分:1)

我遇到了类似的问题,但只是通过改变呼叫顺序解决了这个问题。

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

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

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

gs(a, b, ry);