在python中遇到很多的下滑线,有__init__有__foo有_foo等多种形式,这些下划线有什么区别?
直接上例子:
In [2]: class TestSubLine():
...: def __init__(self):
...: self.__firstname = 'Gang'
...: self._lastname = 'Wa'
...:
In [3]: ts = TestSubLine()
In [4]: print ts.__firstname
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-fe8326af4d4d> in <module>()
----> 1 print ts.__firstname
AttributeError: TestSubLine instance has no attribute '__firstname'
In [5]: print ts._lastname
Wa
In [6]: print ts.__dict__
{'_TestSubLine__firstname': 'Gang', '_lastname': 'Wa'}
例子中,首先出现了__init__:这是表示python内部的一种名字,防止和用户自己的名字有冲突。
__firstname不能打印出来,是因为解析器用_classname__foo来代替这个名字,以区别和其他类相同的命名.
_lastname可以打印出来,因为_foo一般表示自己定义的私有变量
如果还有不清楚的可以看stackoverflow

709

被折叠的 条评论
为什么被折叠?



