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
  question about __repr__ in a class akbarza 4 530 Jan-12-2024, 11:22 AM
Last Post: DeaD_EyE
  Initiating an attribute in a class __init__: question billykid999 8 1,249 May-02-2023, 09:09 PM
Last Post: billykid999
  [Solved] Novice question to OOP: can a method of class A access attributes of class B BigMan 1 1,267 Mar-14-2022, 11:21 PM
Last Post: deanhystad
  newbie question....importing a created class ridgerunnersjw 5 2,571 Oct-01-2020, 07:59 PM
Last Post: ridgerunnersjw
  Class question robdineen 7 3,143 May-30-2020, 05:44 AM
Last Post: Calli
  Question about naming variables in class methods sShadowSerpent 1 1,962 Mar-25-2020, 04:51 PM
Last Post: ndc85430
  Class Question esteel 5 4,013 May-22-2018, 10:27 AM
Last Post: esteel
  First Post/ Class Error Question jvan1601 2 3,370 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