做一个父功能返回超回来吗?
题
有一个检查我需要执行之后,随后的每个步骤中的一个功能,所以我想来定义这一步骤作为一个内的功能的一个函数。
>>> 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返回'a'从内ry?我以为使用超但认为这只是课程。
感谢
还有一点困惑...我只想要返回,如果a==b。如果一个!=b,然后我不想gs到任何回报。
编辑:我现在觉得 装饰 可能是最好的解决方案。
解决方案
这应该允许您随时查看状态,并从外部的函数返回如果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 gs(a,b):
def ry():
if a==b:
return a
return ry()
正如您所提到的功能“步骤”,它似乎像你想要一台发电机:
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,使用新产量语法。)
有一直有点混乱......我 只希望如果== B返回一个。如果 一个!= B,那么我不想GS返回 任何迹象。
检查该那么:
def gs(a,b):
def ry():
if a==b:
return a
ret = ry()
if ret: return ret
# do other stuff
在返回RY()明确而不是只调用它。
我也有类似的问题,但通过简单地改变呼叫的顺序来解决它。
def ry ()
if a==b
gs()
在某些语言如JavaScript甚至可以传递一个函数作为函数的变量:
function gs(a, b, callback) {
if (a==b) callback();
}
gs(a, b, ry);
不隶属于 StackOverflow