Python返回值?

2024-06-26 18:04:20 发布

您现在位置: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()执行逻辑测试,并返回TrueFalse

我需要aModuleEntryPoint()知道testSomething()决定了什么。我不想让aModuleEntryPoint()知道testSomething()是如何得出结论的。

在删除其他功能的同时发布我的实际源代码是一项成就,所以我必须这样设置一般要点。


Tags: falsetruereturnifdefthis条件argument
3条回答

我现在唯一看错的是你需要在第9行的return之前加上testSomething()

我看你的代码的第一个想法是它有点太复杂了。为什么有aFunction呢?你可以直接写信

def aModuleEntryPoint():
    argument = ...
    if argument in (theRightValue, theOtherRightValue, theOtherOtherRightValue)\
       and testSomething():
        doMoreStuff()
    else:
        complain()  

这个if子句将首先检查argument是否是可能的正确值之一,如果是,那么它将继续调用testSomething(),并检查其返回值。只有当返回值为true时,它才会调用doMoreStuff()。如果其中一个测试失败(这就是我使用and的原因),它将complain()

在这里,子函数可能不是合适的封装工具。您希望将内部功能公开给外部实体。Python类提供了比子函数更好的机制来表达这一点。拥有一个类,您可以以一种非常可控的方式公开内部功能的任何部分。

相关问题 更多 >