Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
class question
#1
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")
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  newbie question....importing a created class ridgerunnersjw 5 728 Oct-01-2020, 07:59 PM
Last Post: ridgerunnersjw
  Class question robdineen 7 1,024 May-30-2020, 05:44 AM
Last Post: Calli
  Question about naming variables in class methods sShadowSerpent 1 644 Mar-25-2020, 04:51 PM
Last Post: ndc85430
  Class Question esteel 5 2,242 May-22-2018, 10:27 AM
Last Post: esteel
  First Post/ Class Error Question jvan1601 2 1,908 May-01-2017, 04:21 AM
Last Post: jvan1601

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020