Python ClassesLesson 43Free preview
Python Magic Methods
This lesson is part of Python · All levels
Summary
Magic methods or dunder methods are special __name__-formatted methods called Python internally, rather than by user code. The common examples are __init__ for construction, __str__ for text representation, __len__ for length, and __add__ for addition operator. By using the magic method, your object can behave like a built-in data type.
Key points
- Magic methods always have lines reading on both sides, for example __str__, __repr__, __eq__, and __add__.
- __str__ is used by str(obj) and print(obj); __repr__ is intended for debugging developers.
- __len__ makes an object be given len(), __add__ makes an object be summed by +.
- __eq__ defines the mean of the object's comparison equation using the operator ==.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.