简体   繁体   中英

Python - print values not being returned by function

I'm learning about python at the moment and came across this code:

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:

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"? 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()?

Any help on this would be very appreciated.

Get in the habit of having your functions return values. Functions with no return statement return None by default.

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).

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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