![图片[1]-python如何访问私有变量-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5d919b6c6e0f6307.jpg)
首先,Python 正常访问公有成员变量的方式为:
classPrivateTest: name="private" if__name__=="__main__": pt=PrivateTest() print(pt.name)
输出结果为:
private
Python 中将成员和方法私有化的方式是在成员名或者方法名前面加两个下划线,如下:
classPrivateTest: __name="private" if__name__=="__main__": pt=PrivateTest() print(pt.__name)
运行报错
print(pt.__name) AttributeError:'PrivateTest'objecthasnoattribute'__name'
换个方式
classPrivateTest: __name="private" if__name__=="__main__": pt=PrivateTest() print(pt.name)
运行依然报错
print(pt.name) AttributeError:'PrivateTest'objecthasnoattribute'name'
Python 中访问私有成员变量的正确方式为:实例类.类名_变量名
classPrivateTest: __name="private" if__name__=="__main__": pt=PrivateTest() print(pt._PrivateTest__name)
输出结果
private原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END

















































暂无评论内容