
![]() |
@wtf | |
(Build a custom string class) |
||
1
Replies
6
Views
1 Bookmarks
|
![]() |
@wtf | 10 days |
Dunder (Magic) Methods in Python Lets dive into the world of Pythons dunder methods the ones surrounded by double underscores (_like_this_)! What are Dunder Methods? Dunder (Double UNDERscore) methods are special methods in Python that let you define how objects behave with built-in functions and operators. Examples: - _init_() &8594; Object initialization - _str_() &8594; String representation - _len_() &8594; Length using len() - _add_() &8594; + operator behavior - _eq_() &8594; == comparison Why Use Them? They make your class behave like built-in types (e.g., str, list, etc.) Example: class Book: def _init_(self, title, pages): self.title = title self.pages = pages def _str_(self): return fself.title has self.pages pages def _len_(self): return self.pages book1 = Book(Python Basics, 300) print(book1) Python Basics has 300 pages print(len(book1)) 300 Without _str_, print(book1) shows something like _main_.Book object at 0x... Without _len_, len(book1) raises an error. Popular Dunder Methods & Their Purpose: * _init_ &8594; Constructor * _str_ &8594; Readable string output * _repr_ &8594; Debug representation * _len_ &8594; Length with len() * _eq_ &8594; Equality == check * _add_ &8594; Add with + * _getitem_ &8594; Indexing obj[index] |
||


