Bird
0
0

Which of the following is the correct syntax to define the __str__ method inside a Python class?

easy📝 Syntax Q3 of 15
Python - Magic Methods and Operator Overloading
Which of the following is the correct syntax to define the __str__ method inside a Python class?
Adef str(self): return 'string'
Bdef __str__(self): return 'string'
Cdef __str__(obj): return 'string'
Ddef __string__(self): return 'string'
Step-by-Step Solution
Solution:
  1. Step 1: Recall method signature for __str__

    The __str__ method must be defined with 'self' as the first parameter and named exactly __str__ with double underscores.
  2. Step 2: Check each option

    def __str__(self): return 'string' matches the correct syntax. def str(self): return 'string' misses underscores, def __str__(obj): return 'string' uses wrong parameter name, def __string__(self): return 'string' uses wrong method name.
  3. Final Answer:

    def __str__(self): return 'string' -> Option B
  4. Quick Check:

    Correct __str__ syntax = def __str__(self) [OK]
Quick Trick: Always use double underscores and self parameter for __str__ [OK]
Common Mistakes:
  • Omitting underscores in method name
  • Using wrong parameter name instead of self
  • Naming method incorrectly as __string__

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes