LearnFrenzy
Sign in Take a free test

OOP in Python · Predict the Output · Question 11

Bound methods Answer, explanation & discussion

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

What is the output of the following Python program?

main.py
class Greeter:
    def __init__(self, name):
        self.name = name
    def greet(self, msg="Hi"):
        return f"{msg}, {self.name}"

g = Greeter("Asha")
f = g.greet
print(f(), Greeter.greet(g, "Hello"), f("Bye"))
  • A TypeError
  • B Hi, Asha Hello, Greeter Bye, Asha
  • C Hi, g Hello, g Bye, g
  • D Hi, Asha Hello, Asha Bye, Asha Correct
Correct Answer: Option D

g.greet is a bound method that remembers g. Calling through the class means passing the object yourself.

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