zoukankan      html  css  js  c++  java
  • python中单下划线和双下划线

    # test1.py

    class
    Student(object): def __init__(self): self.__name = "" self.__age = "" self.hobby = "" def _set_age(self): self.__age = 23 print(self.__age) def __set_name(self): self.__name = "Lili" print(self.__name) s = Student() s._set_age() s.__set_name()

    运行test1.py执行结果如下:

    "D:Program Filespython3.6.7python.exe" D:/pythonWorkspace/untitled1019/test/test1.py
    23
    Traceback (most recent call last):
    File "D:/pythonWorkspace/untitled1019/test/test1.py", line 22, in <module>
    s.__set_name()
    AttributeError: 'Student' object has no attribute '__set_name'

    Process finished with exit code 1

    创建对象 s:

    s调用 _set_age 方法, 不会有提示,但是可以强制调用,不会报错;  所以,单下划线的变量或者方法是内部私有, 但是外部可以强制调用;

    s调用__set_name方法,会报没有该属性的错误;  所以, 双下划线的变量或者方法也是内部私有,  外部调用会报错

  • 相关阅读:
    java基础(7)
    log4j日志打印级别动态调整
    前端学习
    windows下 使用vs command tools 和mingw 分别编译 openssl
    收尾作业(3)
    收尾作业(2)
    收尾作业(1)
    收尾作业第一个接口
    图形建模需求
    收尾作业2
  • 原文地址:https://www.cnblogs.com/harryTree/p/11803219.html
Copyright © 2011-2022 走看看