私有变量访问

2019-08-06  本文已影响0人  _PatrickStar
class Student:
    __name = "三毛"
    school = "北大"


print(Student.school)
# print(Student.__name)

如果将# print(Student.__name) 注释拿掉 运行会报错,因为私有变量不能直接访问
报错如下

Traceback (most recent call last):
  File "F:/python/python interview question/training/private_var.py", line 7, in <module>
    print(Student.__name)   #直接访问会报错 不存在__name属性
AttributeError: type object 'Student' has no attribute '__name'

打印Student的方法内置方法

class Student:
    __name = "张三"  #私有变量 单侧双下滑线加名字
    school = "北大"

print(Student.school)
# print(Student.__name)   #直接访问会报错 不存在__name属性
print(dir(Student))

第一个内置方法Student__name,所以猜测私有变量访问方法是通过类名+变量名的形式访问,如下:

['_Student__name', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'school']

于是打印 _Student__name验证

class Student:
    __name = "张三"  #私有变量 单侧双下滑线加名字
    school = "北大"
    __age = 18

# print(Student.school)
# print(Student.__name)   #直接访问会报错 不存在__name属性
# print(dir(Student))
print(Student._Student__name)

输出结果:张三
验证成功!
结论:私有变量访问方法是通过_类名+变量名的形式访问

上一篇 下一篇

猜你喜欢

热点阅读