Python & FastAPI•Part 2: Python Core Language, Internals & Runtime (6 - 25)
Dunder methods: `__str__` vs `__repr__`, `__new__` vs `__init__`:
In Simple Words:
__str__: User-friendly readable string for end users.__repr__: Unambiguous string for developers and debugging (eval(repr(obj)) == obj).__new__: Allocates and returns the new instance in memory (used in Singletons and immutable types).__init__: Initializes the newly created instance attributes.
python
class User:
def __init__(self, name: str, id: int):
self.name = name
self.id = id
def __str__(self):
return self.name
def __repr__(self):
return f"User(name={self.name!r}, id={self.id})"