LearnFrenzy
Sign in Take a free test

OOP in Python · Predict the Output · Question 15

Methods that return self Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

What is the output of the following Python program?

main.py
class Text:
    def __init__(self, s):
        self.s = s
    def strip(self):
        self.s = self.s.strip()
        return self
    def upper(self):
        self.s = self.s.upper()
        return self

t = Text("  hello ")
print(repr(t.strip().upper().s), repr(t.s))
  • A 'HELLO' ' hello '
  • B ' HELLO ' 'HELLO'
  • C 'HELLO' 'HELLO' Correct
  • D AttributeError
Correct Answer: Option C

Each method changes the object and returns it, so calls chain and t itself is modified.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links