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

Jia*_*aro 3 python return class function 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
Run Code Online (Sandbox Code Playgroud)

那么如何让gs从ry中返回'a'?我想过使用超级,但认为这只适用于课程.

谢谢

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

编辑:我现在认为装饰者可能是最好的解决方案.

S.L*_*ott 10

你的意思是?

def gs(a,b):
    def ry():
        if a==b:
            return a
    return ry()
Run Code Online (Sandbox Code Playgroud)


Mik*_*ers 4

这应该允许您继续检查状态并从外部函数返回(如果 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]
Run Code Online (Sandbox Code Playgroud)