簡體   English   中英

如何僅從 Python 中的 function 獲取返回值?

[英]How to get just the return value from a function in Python?

我正在嘗試通過 Python 學習編程,我想知道是否有可能只獲得 function 的返回值而不是其他部分。 這是代碼:

比方說,這是主要的function:

variable_a = 5

while variable_a > 0 :            
    input_user = raw_input(": ") 
    if input_user == "A":    
            deduct(variable_a)
            variable_a = deduct(variable_a)    
    else:
        exit(0)

那么這是扣除function:

def deduct(x):     
    print "Hello world!"  
    x = x - 1  
    return x

發生的情況是,它會進行計算並扣除,直到 variable_a 達到 0。但是,“Hello world”被打印兩次,我認為是因為variable_a = deduct(variable_a) (如果我錯了,請糾正我)。 所以我在想,我可以只捕獲 deduct() 的返回值而不捕獲 rest 嗎? 所以在這種情況下,在通過 deduct() 之后,variable_a 將只有一個簡單的值 2(沒有“Hello world.”)。

我錯過了什么嗎? :?

編者注:我刪除了空白行,因此可以將其粘貼到 REPL。

“Hello world”的打印是所謂的副作用 - 由 function 產生的東西,它沒有反映在返回值中。 您要問的是如何調用 function 兩次,一次產生副作用,一次捕獲 function 返回值。

事實上,你根本不必調用它兩次——一次就足以產生兩種結果。 只需在一次且唯一的調用中捕獲返回值:

if input_user == "A":
    variable_a = deduct(variable_a)
else: 

如果您不希望 function 打印 output,正確的解決方案是不要在其中使用print :P

第一次調用deduct時,它除了打印該消息之外什么都不做,因此您可能只需刪除該行就可以了。

但是,一種略顯凌亂的方式來抑制打印語句。 您可以使用不執行任何操作的占位符臨時替換程序的 output 文件。

import sys

class FakeOutput(object):
    def write(self, data):
        pass

old_out = sys.stdout
sys.stdout = FakeFile()

print "Hello World!" # does nothing

sys.stdout = old_out
print "Hello Again!" # works normally

你甚至可以制作一個上下文管理器來使這更方便。

import sys

class FakeOutput(object):
    def __enter__(self):
        self.out_stdout = sys.stdout
        sys.stdout = self
        return self

    def __exit__(self, *a):
        sys.stdout = self.out_stdout

    def write(self, data):
        pass

print "Hello World!" # works

with FakeOutput():
    print "Hello Again!" # doesn't do anything

print "Hello Finally!" # works

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM