Python 返回值?
我该怎么做呢?我可以这样做吗?
def aFunction(argument):
def testSomething():
if thisValue == 'whatItShouldBe':
return True
else:
return False
if argument == 'theRightValue': # this is actually a switch using elif's in my code
testSomething()
else:
return False
def aModuleEntryPoint():
if aFunction(theRightValue) == True:
doMoreStuff()
else:
complain()
aModuleEntryPoint()
aModuleEntryPoint()
在开始做事情之前,需要先确认一个条件是否为真。由于封装的原因,aModuleEntryPoint
并不知道怎么检查这个条件,但 aFunction()
里面有一个叫 testSomething()
的子函数,它知道怎么检查这个条件。于是,aModuleEntryPoint()
调用了 aFunction(theRightValue)
。
因为 theRightValue
作为参数传给了 aFunction()
,所以 aFunction()
会调用 testSomething()
。testSomething()
会进行逻辑测试,然后返回 True
(真)或者 False
(假)。
我需要 aModuleEntryPoint()
知道 testSomething()
的判断结果,但我不想让 aModuleEntryPoint()
知道 testSomething()
是怎么得出这个结论的。
其实,能够在去掉其他函数和杂七杂八的内容后,发布我的实际代码是个成就,所以我只能把大概念设置成这样。
3 个回答
我看到你的代码,第一感觉是有点复杂。为什么要用aFunction
呢?你其实可以直接写
def aModuleEntryPoint():
argument = ...
if argument in (theRightValue, theOtherRightValue, theOtherOtherRightValue)\
and testSomething():
doMoreStuff()
else:
complain()
这个if
语句会先检查argument
是不是正确的值之一。如果是的话,它就会继续调用testSomething()
,并检查这个函数返回的结果。只有当这个结果是对的时候,它才会调用doMoreStuff()
。如果其中任何一个检查失败(这就是我用and
的原因),它就会执行complain()
。
也许在这里使用子函数并不是最合适的选择。你想把内部功能展示给外部使用者。相比于子函数,Python 的类提供了一种更好的方式来实现这个目的。通过使用类,你可以以一种非常受控的方式,展示你想要的内部功能的某些部分。
我现在看到的唯一问题是,你在第9行的 testSomething()
前面需要加一个 return
。