【问题标题】:Returning a print statement still shows the value [duplicate]返回打印语句仍然显示值[重复]
【发布时间】:2018-11-05 04:40:16
【问题描述】:

我测试了以下代码:

In [266]: def foo(): 
     ...:     print("yes") 
     ...:                                                                                                         

In [267]: def bar(): 
     ...:     return foo() 
     ...:                                                                                                         

In [268]: bar()                                                                                                   
yes

In [269]: x = bar()                                                                                               
yes

我对结果很不解,它充当

In [274]: def foo(): 
     ...:     return print("yes %.1f" %12.333) 
     ...:      
     ...:                                                                                                         

In [275]: foo()                                                                                                   
yes 12.3

我该如何理解?很像 shell 脚本 shell 的命令替换 echo $(ls)

【问题讨论】:

  • 你调用了bar(),它调用了foo(),它打印(不是返回,而是打印)“是”。有什么困惑?
  • 好像没试过x = bar(); print(x)

标签: python


【解决方案1】:

在方法中你可以做一些动作而不返回任何东西,而是直接显示结果,例如打印或返回结果,让另一部分代码使用它。

所以,我想解释一下你的代码在做什么:

In [266]: def foo(): 
     ...:     print("yes") # you are printing 'yes'
     ...:                                                                                                         

In [267]: def bar(): 
     ...:     return foo()  #you are returning a foo method
     ...:                                                                                                         

In [268]: bar()    # you are not directly calling foo()                                                                                            
yes

In [269]: x = bar()  # you are not directly calling foo() and this is equivalent to x = print('yes')                                                                                             
yes

只是一个简单的例子:

>>> def foo():
...     print('Yes')
...
>>> def boo():
...     return foo()
...
>>> boo()
Yes
>>> x = boo() 
Yes
>>> x = print('Yes')
Yes
>>> x = 'Yes' # it is not printed
>>>

所以,基本上,shell 不会回显任何变量,除非它在 ​​print() 中使用 但是,如果您的方法返回一个值,它将被打印出来。基本上在shell return 也会起到打印作用。

>>> def noo():
...     return 'Yes'
...
>>> noo()
'Yes'
>>>

【讨论】:

  • “但是,如果您的方法返回一个值,它将被打印” - 仅在 REPL 中
【解决方案2】:

根据你的代码和解释,我认为你误用了shell脚本

在shell中返回一个字符串(例如)你可以这样做

#!/bin/sh
foo()
{
  echo "my_string"
}

A=$(foo)
echo $A

$A 的值将是“my_string”

在 python 中做同样的事情

def foo():
    return "my_string"

a = foo()
print(a)

我们在 shell 脚本中使用 echo 技巧的原因是因为 shell 中的 return 只能返回 0-255 之间的值,这并不总是我们想要做的(如在你的示例中或我的示例中我们想要返回一个字符串)

如果我的答案不够清楚,请告诉我,感谢 cmets,我会改进它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 2015-08-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    相关资源
    最近更新 更多