即使它有一个return语句,我的函数仍然返回None [英] My function keeps returning None even though it has a return statement
问题描述
我有一个非常短的函数,它位于一个继续返回 None
的类中,尽管我已经将之前的打印语句转换为return语句,下面是我有:
$ b $ pre $ def解释(self):
return(print('Wear a',self.getColor() ,'shirt')
该语句会打印出来,但每次打印没有
在下一行,请让我知道我怎么能阻止这种情况的发生!
print
的输出,而 print
函数本身的值是 None
,这就是返回的结果。 如果您希望返回值并将其打印出来,你可以这样做:
def explain(self):
string ='穿一个'+ self.getColor ()+'shirt'
print(string)
返回字符串
如果只需要返回值,只需删除上面的print语句,稍后可以打印。
I have a very short function located within a class that keeps returning None
, even though I have turned what was previously a print statement into a return statement, here's what I have:
def explain(self):
return(print('Wear a', self.getColor(), 'shirt')
The statement will print out but every time it prints None
on the next line, please let me know how I can stop this from happening!
This is because the output of the print
is printed on the terminal, and the value of the print
function in itself is a None
, which is what is returned.
If you wish to return the value as well as print it, you can do something like:
def explain(self):
string = 'Wear a' + self.getColor() + 'shirt'
print(string)
return string
If only returning the value is needed, simply remove the print statement in the above and you can print it later.
这篇关于即使它有一个return语句,我的函数仍然返回None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!