gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:56 25 4
gpt4 key购买 nike

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

它打印bbbbbbbbbbbbbbbbcccc

为什么能打印出这些,不就是_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.

关于python - 这个地方的_b和b有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1943863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com