victory的博客

长安一片月,万户捣衣声

0%

python | Python变量单前下划线与双前下划线的区别

Python变量单前下划线与双前下划线的区别

_variable

表面上为私有,实际在外部可以访问

__variable

实际上的私有,只能在内部访问,不能在外部访问(报错)

_ variable _

魔法方法(magic method)/ 特殊方法

Example

class TestPrivacy(object):
    _name = 'hello' 
    __name = 'world'
    
print(TestPrivacy._name) # Output:'hello'
print(TestPrivacy.__name) # Output: AttributeError: type object 'TestPrivacy' has no attribute '__name'