My function keeps returning None even though it ha

2020-05-10 08:44发布

问题:

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!

回答1:

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.



回答2:

return statement is not a function. It is a control flow construct (like if-else). It is what lets you "take data with you between function calls". So, you can't return print, because it's not a function, it's a reserved word. But since print is a statement, you see it's output on the terminal, but None as well, since nothing is returned by the function. If you wish to return a string, do like this :

return 'Wear a ' + self.getColor() + ' shirt'