Skip to main content
 首页 » 编程设计

python之这个地方的_b和b有什么区别

2025年05月04日12telwanggs

class a: 
    def __init__(self): 
        self._b()#why here use _b,not b,What's the difference 
        self._c='cccc'#why here use _c,not c,What's the difference 
    def _b(): 
        print 'bbbb' 

a.py

class a: 
    def __init__(self): 
        self._b()#why here use _b,not b,What's the difference 
        self._c='cccc'#why here use _c,not c,What's the difference 
    def _b(self): 
        print 'bbbb' 

b.py

from  a import * 
b=a() 
b._b() 
print b._c 

它打印 bbbb bbbb bbbb bbbb cccc

为什么能打印出这些,不就是_b和_c私有(private)变量吗。

请您参考如下方法:

在变量名或函数名前加下划线是 Python 中的一种约定,表示该变量是私有(private)的。来自 the docs :

Private” instance variables that cannot be accessed except from inside an object, don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.