# test1.pyclass 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 Files\python3.6.7\python.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方法,会报没有该属性的错误; 所以, 双下划线的变量或者方法也是内部私有, 外部调用会报错