Magicmethods
Source: 8-Class And Objects/8.6-magicmethods.ipynb
Start here — no coding background needed
What you will learn
Special double-underscore methods — Python hooks.
In simple words
Methods like `__str__` control how printing looks — advanced but useful later.
Group data and actions together — used in bigger apps; go slow, use analogies.
Easy example — run this first. Change values and press Run again.
Runs in your browser via Pyodide — no server. First run may take a few seconds.
Reference notes (from full bootcamp)
Optional — deeper detail for when you are ready
Magic Methods
Magic methods in Python, also known as dunder methods (double underscore methods), are special methods that start and end with double underscores. These methods enable you to define the behavior of objects for built-in operations, such as arithmetic operations, comparisons, and more.
Magic Methods
Magic methods are predefined methods in Python that you can override to change the behavior of your objects. Some common magic methods include:
Expected (from notebook): "\n__init__': Initializes a new instance of a class.\n__str__: Returns a string representation of an object.\n__repr__: Returns an official string representation of an object.\n__len__: Returns the length of an object.\n__getitem__: Gets an item from a container.\n__setitem__: Sets an item in a container.\n"
Runs in your browser via Pyodide — no server. First run may take a few seconds.
Expected (from notebook): ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
Runs in your browser via Pyodide — no server. First run may take a few seconds.
Expected (from notebook): <__main__.Person object at 0x0000029E5D059940>
Runs in your browser via Pyodide — no server. First run may take a few seconds.
Expected (from notebook): <__main__.Person object at 0x0000029E5D31D4C0>
Runs in your browser via Pyodide — no server. First run may take a few seconds.
Expected (from notebook): Anshul,34 years old Person(name=Anshul,age=34)
Runs in your browser via Pyodide — no server. First run may take a few seconds.
Practice test — try yourself
Write code, press Check. Wrong answer shows the correct code to copy & run.
You learned "Magicmethods". Use print() to show: Done: Magicmethods
Hint: Use one print() with the exact text.