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:Omitting 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 Constructors and Object Initialization - __init__ method behavior - Quiz 11easy Constructors and Object Initialization - Self reference - Quiz 14medium Context Managers - Why context managers are needed - Quiz 2easy Custom Exceptions - Creating exception classes - Quiz 14medium Custom Exceptions - Best practices for custom exceptions - Quiz 9hard Custom Exceptions - Exception hierarchy - Quiz 6medium Custom Exceptions - Adding custom attributes - Quiz 3easy File Handling Fundamentals - Opening and closing files - Quiz 15hard Inheritance and Code Reuse - Method overriding - Quiz 2easy Structured Data Files - Dictionary-based CSV handling - Quiz 10hard