简体   繁体   English

Python-函数未返回打印值

[英]Python - print values not being returned by function

I'm learning about python at the moment and came across this code: 我目前正在学习python,并遇到了以下代码:

class Simple:
    def __init__(self, str):
        print("Inside the Simple constructor")
        self.s = str
    # Two methods:
    def show(self):
        print(self.s)
    def showMsg(self, msg):
        print(msg + ':',
        self.show()) 

I'm playing around with it in the python shell and did the following: 我正在python shell中进行操作,并执行以下操作:

x = Simple("A constructor argument")
x.show()

which outputs: 输出:

A constructor argument

This makes sense to me, however I then input: 这对我来说很有意义,但是我随后输入:

x.showMsg("A message")

Which outputs: 哪个输出:

A constructor argument
A Message:None

This is where I'm confused. 这就是我感到困惑的地方。 Why is the call to the self.show() in showMsg() resulting in "None" when x.Show() results in "A constructor argument"? 当x.Show()产生“构造函数参数”时,为什么对showMsg()中的self.show()的调用导致“ None”? I thought that self was a placeholder until an instance of the class was created, which would mean that self.show() in this case would be equivalent to x.show()? 我以为在创建类实例之前self是一个占位符,这意味着在这种情况下self.show()等同于x.show()?

Any help on this would be very appreciated. 任何帮助,将不胜感激。

Get in the habit of having your functions return values. 养成让函数return值的习惯。 Functions with no return statement return None by default. 没有return语句的函数默认情况下返回None

Here is an example of how you might rewrite your program: 这是一个如何重写程序的示例:

class Simple:
    def __init__(self, str):
        self.s = str
    # Two methods:
    def show(self):
        return self.s
    def showMsg(self, msg):
        return msg + ': ' + self.show()

x = Simple("A constructor argument")

print(x.show())
# A constructor argument

print(x.showMsg('A message'))
# A message: A constructor argument

While you can have print inside your class, it's a better idea to have your class handle logic and have flexibility with what you do with the results (print them, store them in a list, pass them on to another function, etc). 虽然可以在类中进行print ,但最好是让类处理逻辑并灵活处理结果(打印结果,将其存储在列表中,将其传递给另一个函数等)。

What the show() method in your class does is just print the stored message, however, what showMsg is trying to do concatenating some msg with the stored one, by calling the show method, however, since show() returns nothing, or None, it will get cat'ed just like that, you will have to change your method to either: 类中的show()方法所做的只是打印存储的消息,但是, showMsg试图通过调用show方法来将某些msg与存储的msg连接起来,但是,因为show()不返回任何内容,否则返回None ,它会像这样受到关注,您将不得不将您的方法更改为:

def show(self):
    return self.s

or 要么

def show(self):
    print(self.s)
    return self.s

In the second case you will retain the functionality for both cases, but it is bad practice 在第二种情况下,您将保留这两种情况的功能,但这是不明智的做法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM