You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+33Lines changed: 33 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -1704,6 +1704,39 @@ The Subclass relationships were expected to be transitive, right? (i.e. if `A` i
1704
1704
1705
1705
---
1706
1706
1707
+
### Mangling time!
1708
+
1709
+
Suggested by @Lucas-C in [this](https://github.com/satwikkansal/wtfpython/issues/36) issue.
1710
+
1711
+
1712
+
```py
1713
+
# Name mangling:
1714
+
class Yo(object):
1715
+
def__init__(self):
1716
+
self.__honey =True
1717
+
self.bitch =True
1718
+
```
1719
+
1720
+
**Output:**
1721
+
```py
1722
+
>>> Yo().bitch()
1723
+
True
1724
+
>>> Yo().__honey()
1725
+
AttributeError: 'Yo'object has no attribute '__honey'
1726
+
>>> Yo()._Yo__honey
1727
+
True
1728
+
```
1729
+
1730
+
Why did `Yo()._Yo__honey` worked? Only Indian readers would understand.
1731
+
1732
+
#### 💡 Explanation:
1733
+
1734
+
* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces.
1735
+
* In Python, the interpreter modifies (mangles) the class member names starting with`__` (double underscore) andnot ending with more than one trailing underscore by addding `_NameOfTheClass`in frot.
1736
+
* So, to access `__honey` attribute, we are required to append `_Yo` to the front which would prevent conflicts with a same name attribute defined inany other class.
1737
+
1738
+
---
1739
+
1707
1740
### Let's see if you can guess this?
1708
1741
1709
1742
Suggested by @PiaFraus in [this](https://github.com/satwikkansal/wtfPython/issues/9) issue.
0 commit comments