PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Python · Theory

Magic methods

← All stacks

Theory

95/268

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>.

Exam tip

Name three dunders and what built-in they power.

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>.

Short notes

  • Def__name__ methods hook built-ins.
  • Rule__init__ / __str__ / __len__ first.
  • Rememberprint uses __str__.

Questions

1

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

2

What does the example print, and why?

3

What mistake do freshers make with Magic methods?

Previous← CLI argumentsNextStack & Queue →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.