【发布时间】:2013-10-03 07:43:54
【问题描述】:
首先我应该说我不知道这个话题是否足够好,但是一句话解释我的问题真的很难。
之后,我会向你解释整个事件;
我正在用 python 编写一个程序,其中我有一个带有一些方法的类,其中一个方法 (method1),在配置数据列表和方法 2 的循环中运行该类的另一个方法 (method2)我调用了该类的其他一些方法。代码是这样的:
class myClass():
def method1(self):
for member in some_list:
method2(member)
def method2(self, member):
do something with the member
self.method3()
self.method4()
self.method5()
...
在 method2 中,有些情况我想从方法内部停止 method2。我的意思是有时我想在方法 3 或方法 4 中停止方法 2。
我不想使用assert,因为它会停止整个程序,我只想跳过这个特殊成员并继续方法1中的循环。换句话说,列表中的某些成员造成了一些我们无法继续 method2 的情况,我们应该停止并为列表的下一个成员启动 method2 的过程。
我现在可以返回 True 和 False 值并检查它以决定是否要通过 return 关键字停止,但我不想使用这种方法。我真正想要的是编写一个方法,在这些情况下,我调用它并且该方法停止 method2 执行并返回到 method1 中的第一个循环以选择另一个成员。我可以写一个例子:
def method3(self):
do something
if some_special_situation:
method_stop()
else:
continue execution
def method_stop():
do something to stop the method which is calling it
and the method that the first method is called there
I mean if method2 is calling method3 and method3 is calling method_stop
method_stop should stop both method2 and method3
我不知道这个问题有多清楚,但是如果您需要任何解释,请问我。 我将不胜感激。
【问题讨论】:
-
你的问题没有答案,因为在 Python 中破坏调用堆栈上的东西是不可能的。使用异常或
return值以获得正确的解决方案。
标签: python methods class-method