Python 访问私有成员变量

Python 访问私有成员变量

python 在属性名或方法名前加两个下划线表示私有,如下:

class PrivateTest:
    __name = "private"
    

if __name__ == "__main__":
    pt = PrivateTest()
    print(pt.__name)

运行报错:

AttributeError: 'PrivateTest' object has no attribute '__name'

Python 中访问私有成员变量的正确方式为:实例类._类名__变量名

class PrivateTest:
    __name = "private"


if __name__ == "__main__":
    pt = PrivateTest()
    print(pt._PrivateTest__name)

输出结果:

private