Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使父函数返回-超级返回?_Python_Class_Function_Return_Parent - Fatal编程技术网

Python 使父函数返回-超级返回?

Python 使父函数返回-超级返回?,python,class,function,return,parent,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(

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

>>> 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。如果一个=b、 那我还不想让gs归还任何东西

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

你的意思是

def gs(a,b):
    def ry():
        if a==b:
            return a
    return ry()
显式返回ry(),而不是仅调用它

有点混乱。。。我 仅当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
当您在函数中提到“步骤”时,似乎您想要一个生成器:

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开始,生成器现在也可以作为协同程序使用。)

这应该允许您不断检查状态,并在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]

我有一个类似的问题,但通过简单地改变通话顺序就解决了

def ry ()
    if a==b 
        gs()
在某些语言(如javascript)中,您甚至可以将函数作为函数中的变量传递:

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

gs(a, b, ry);

这并不是我问题的真正答案,但它确实解决了我试图解决的问题:)@All:如果你想让外部函数保持正常的函数,那么你只能在内部函数中使用收益率,而不必迭代结果。这有点粗糙,但我喜欢它!非常聪明:)