Skip to content

Commit 7909c0b

Browse files
committed
Add example: Mangling time!
1 parent 0da5243 commit 7909c0b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1704,6 +1704,39 @@ The Subclass relationships were expected to be transitive, right? (i.e. if `A` i
17041704
17051705
---
17061706
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) and not 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 in any other class.
1737+
1738+
---
1739+
17071740
### Let's see if you can guess this?
17081741
17091742
Suggested by @PiaFraus in [this](https://github.com/satwikkansal/wtfPython/issues/9) issue.

0 commit comments

Comments
 (0)