类中的函数在不返回语句的情况下不返回任何值

2024-10-03 21:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚学习了python编程中的类(仍在学习),并开始使用它进行实验,发现我的代码在输出中给出了none语句,但在函数中没有使用任何return

我的代码


class GreetingMessage:
    def welcome_message(self):
        print("you are welcome to python")
    def thank_you_message(self):
        print("Ok Bye Thank You")
    def on_process_message(self):
        print("process is on progress")
        

msg1 = GreetingMessage()

print(msg1.welcome_message())
print(msg1.on_process_message())
print(msg1.thank_you_message())

输出:

欢迎您使用python 没有一个 这一进程正在取得进展 没有一个 好的,再见,谢谢 没有


Tags: 代码selfnoneyoumessageondef编程
3条回答

函数将自动返回None,除非您编写了return语句。如果已经编写了print语句,则无需在类外再次编写print。只需调用该方法

msg1.welcome_message()
msg1.on_process_message()
msg1.thank_you_message()

如果您想要一个return语句,那么在调用该方法时必须在类外编写print

编辑的代码将是:

class GreetingMessage:
    def welcome_message(self):
        return "you are welcome to python"
    def thank_you_message(self):
        return "Ok Bye Thank You"
    def on_process_message(self):
        return "process is on progress"
    

msg1 = GreetingMessage()

print(msg1.welcome_message())
print(msg1.on_process_message())
print(msg1.thank_you_message())

您的函数没有return值,因此,函数返回None,您可以在函数中使用return而不是print,如下所示:

class GreetingMessage:
    def welcome_message(self):
        return ("you are welcome to python")
    def thank_you_message(self):
        return ("Ok Bye Thank You")
    def on_process_message(self):
        return ("process is on progress")
        

msg1 = GreetingMessage()

print(msg1.welcome_message())
print(msg1.on_process_message())
print(msg1.thank_you_message())

输出:

you are welcome to python
process is on progress
Ok Bye Thank You

请参见此示例,此问题发生在您的程序中:

>>> def fun_tst():
...    print('hi')
>>> print(fun_tst())
hi
None



>>> def fun_tst():
...    return ('hi')    
>>> print(fun_tst())
hi

如果在代码中不使用返回函数,它将自动返回None。但是,如果您正在使用的函数已经自行打印,则您没有义务打印该函数的结果。你可以直接写:

msg1.welcome_message()
msg1.on_process_message()
msg1.thank_you_message()

相关问题 更多 >