Python Forum
class question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: class question (/thread-24482.html)



class question - jrauden - Feb-16-2020

When you run this little program it prints out:
Inside the Simple constructor
constructor argument
constructor argument
A message: None

What i don't get is how "constructor argument" prints out twice in a row? I'm sure it has something to do with the comma in the showMsg(). Can anybody please explain:
1. why does it print out this way, i guess i am following the code wrong
2. what exactly that comma does?
3. does Python not print anything inside the showMsg() print statement until after the show() function has run a 2nd time?

Thank you for any help, i know this is probably very basic, just picking up coding again for the first time in 17 years....used C back then in college.

class Simple:
    def __init__(self, str):
        print("Inside the Simple constructor")
        self.s = str

    def show(self):
        print(self.s)
    def showMsg(self, msg):
        print(msg + ':',
        self.show()) # Calling another method

if __name__ == "__main__":
    # Create an object:
    x = Simple("constructor argument")
    x.show()
    x.showMsg("A message")



RE: class question - ibreeden - Feb-16-2020

Hello jrauden,
This is because function "show()" does not return anything (= None). So when you do:
        print(msg + ':',
        self.show())
... it will print:
Output:
A message : None
To get a more satisfying result you may change your code like this:
class Simple:
    def __init__(self, str):
        print("Inside the Simple constructor")
        self.s = str
 
    def show(self):
        return(self.s)

    def showMsg(self, msg):
        print(msg + ':',
        self.show()) # Calling another method
 
if __name__ == "__main__":
    # Create an object:
    x = Simple("constructor argument")
    print(x.show())
    x.showMsg("A message")
Output:
Inside the Simple constructor constructor argument A message: constructor argument