Skip to content

Commit 118f51d

Browse files
committed
Add new example: Deep Down, we're all the same
1 parent 78a1218 commit 118f51d

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

README.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1736,6 +1736,52 @@ Why did `Yo()._Yo__honey` worked? Only Indian readers would understand.
17361736
17371737
---
17381738
1739+
### Deep down, we're all the same.
1740+
1741+
Suggested by @Lucas-C in [this](https://github.com/satwikkansal/wtfpython/issues/36) issue.
1742+
1743+
1744+
```py
1745+
class WTF:
1746+
pass
1747+
```
1748+
1749+
**Output:**
1750+
```py
1751+
>>> WTF() == WTF() # two different instances can't be equal
1752+
False
1753+
>>> WTF() is WTF() # identities are also different
1754+
False
1755+
>>> hash(WTF()) == hash(WTF()) # hashes _should_ be different as well
1756+
True
1757+
>>> id(WTF()) == id(WTF())
1758+
True
1759+
```
1760+
1761+
1762+
#### 💡 Explanation:
1763+
1764+
* When `id` was called, Python created a `WTF` class object and passed it to the `id` function. The `id` function takes its `id` (its memory location), and throws away the object. The object is destroyed.
1765+
* When we do this twice in succession, Python allocates the same memory location to this second object as well. Since (in CPython) `id` uses the memory location as the object id, the id of the two objects is the same.
1766+
* So, object's id is only unique for the lifetime of the object. After the object is destroyed, or before it is created, something else can have the same id.
1767+
* But why did the `is` operator evaluated to `False`? Let's see with this snippet.
1768+
```py
1769+
class WTF(object):
1770+
def __init__(self): print("I ")
1771+
def __del__(self): print("D ")
1772+
```
1773+
1774+
**Output:**
1775+
```py
1776+
>>> WTF() is WTF()
1777+
I I D D
1778+
>>> id(WTF()) == id(WTF())
1779+
I D I D
1780+
```
1781+
As you may observe, the order in which the objects are destroyed is what made all the difference here.
1782+
1783+
---
1784+
17391785
### Let's see if you can guess this?
17401786
17411787
Suggested by @PiaFraus in [this](https://github.com/satwikkansal/wtfPython/issues/9) issue.

0 commit comments

Comments
 (0)