首先,Python 正常访问公有成员变量的方式为:
class PrivateTest: name = "private" if __name__ == "__main__": pt = PrivateTest() print(pt.name)
输出结果为:
private
Python 中将成员和方法私有化的方式是在成员名或者方法名前面加两个下划线,如下:
class PrivateTest: __name = "private" if __name__ == "__main__": pt = PrivateTest() print(pt.__name)
运行报错
print(pt.__name) AttributeError: 'PrivateTest' object has no attribute '__name'
换个方式
class PrivateTest: __name = "private" if __name__ == "__main__": pt = PrivateTest() print(pt.name)
运行依然报错
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
更多学习内容,请点击。