Magic methods — Python Technical Interview Questions & Answers

Magic methods

Magic methods

  • Magic methods (dunders) start and end with __. __init__ constructs. __str__ is print(). __len__ is len(obj). They hook your class into Python’s built-in syntax.
  • Write one: class Student with __str__ returning the name. print(s) should show Asha, not <__main__.Student>.
  • Magic methods — output: Asha. __str__ is what print uses. Without it you would see <Student object>.

Technical Interview Tip: Name three dunders and what built-in they power.

Code Examples for Magic methods

Example

# Magic methods
class Student:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return self.name
print(Student("Asha"))

Magic methods — output: Asha. __str__ is what print uses. Without it you would see <Student object>.

How to Explain Magic methods to an Interviewer

Explain Magic methods as if you are teaching a junior — definition, then one tiny script.

__name__ methods hook built-ins. __init__ / __str__ / __len__ first.

What does the example print, and why?

Magic methods — output: Asha

What mistake do freshers make with Magic methods?

print uses __str__.