Skip to content

Commit 5cab0bf

Browse files
committed
Add example for __add__ dunder method in README.md and implement corresponding example script
1 parent 3f75ce1 commit 5cab0bf

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

python_utils/dunder_methods/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
##### `__lt__`
1010
- [Comparison for less-than operation](__lt__1.py)
1111

12+
##### `__add__`
13+
- [Adding objects with the `+` operator](__add__1.py)
14+
1215
##### `__format__`
1316
- [Custom string formatting](__format__1.py)
1417
- [Custom string formatting](__format__2.py)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from typing import Self
2+
3+
4+
class Fruit:
5+
def __init__(self, *, name: str, grams: float) -> None:
6+
self.name = name
7+
self.grams = grams
8+
9+
def __add__(self, other: Self) -> bool:
10+
return self.grams + other.grams
11+
12+
13+
def main() -> None:
14+
f1: Fruit = Fruit(name='Apple', grams=100)
15+
f2: Fruit = Fruit(name='Banana', grams=150)
16+
17+
print(f1 + f2) # 250
18+
19+
20+
if __name__ == '__main__':
21+
main()

0 commit comments

Comments
 (0)