Skip to content

Instantly share code, notes, and snippets.

@MOON-CLJ
Last active December 19, 2015 21:19
Show Gist options
  • Save MOON-CLJ/6019306 to your computer and use it in GitHub Desktop.
Save MOON-CLJ/6019306 to your computer and use it in GitHub Desktop.
name mangling in python
In [29]: class foo():
....: def __init__(self):
....: self.__x = 1
....:
In [30]: r1 = foo()
In [31]: r1.__x
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-31-32786e7560ef> in <module>()
----> 1 r1.__x
AttributeError: foo instance has no attribute '__x'
In [32]: r1.__y = 1
In [33]: r1.__y
Out[33]: 1
In [35]: print r1.__y
1
这里的__x __y为什么会有区别呢
In [40]: class foo():
....: def __init__(self):
....: self.__x = 1
....: self.y = 1
....:
In [41]: r1 = foo()
In [42]: r1.y
Out[42]: 1
In [43]: r1.__x
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-43-32786e7560ef> in <module>()
----> 1 r1.__x
AttributeError: foo instance has no attribute '__x'
In [44]: r1.__dict__
Out[44]: {'_foo__x': 1, 'y': 1}
In [45]: r1._foo__x
Out[45]: 1
In [46]: r1._foo__x = 2
In [47]: r1._foo__x
Out[47]: 2
In [48]: r1.__z = 1
In [49]: r1.__dict__
Out[49]: {'__z': 1, '_foo__x': 2, 'y': 1}
http://docs.python.org/2/reference/expressions.html#atom-identifiers
https://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_Python
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment