Python - Magic Methods and Operator OverloadingWhich 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'Check Answer
Step-by-Step SolutionSolution: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.Step 2: Check each optiondef __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.Final Answer:def __str__(self): return 'string' -> Option BQuick Check:Correct __str__ syntax = def __str__(self) [OK]Quick Trick: Always use double underscores and self parameter for __str__ [OK]Common Mistakes:MISTAKESOmitting underscores in method nameUsing wrong parameter name instead of selfNaming method incorrectly as __string__
Master "Magic Methods and Operator Overloading" in Python9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Python Quizzes Classes and Object Lifecycle - Object lifecycle overview - Quiz 13medium Exception Handling Fundamentals - Common exception types - Quiz 6medium Exception Handling Fundamentals - Common exception types - Quiz 13medium Exception Handling Fundamentals - Common exception types - Quiz 4medium File Reading and Writing Strategies - Overwrite vs append behavior - Quiz 3easy Inheritance and Code Reuse - Extending parent behavior - Quiz 4medium Modules and Code Organization - __name__ and __main__ behavior - Quiz 13medium Multiple Inheritance and Method Resolution - Best practices for multiple inheritance - Quiz 12easy Object-Oriented Programming Foundations - Real-world modeling using objects - Quiz 14medium Structured Data Files - Serializing and deserializing JSON - Quiz 15hard