源于https://docs.python.org/zh-cn/3/tutorial/classes.html#class-and-instance-variables
自己做了一下测试,代码如下:
class class1():
'''
类变量和类方法,个人认为只设置公有就好了。如果类变量设置为不公有,就没有什么意义了
'''
class_variable=1
def __init__(self):
self.public_variable=4
self._protected_variable=5
self.__private_variable=6
def public_method(self):
print('public method')
def _protect_method(self):
print('_protect method')
def __private_method(self):
print('__private method')
def get_para(self):
return self.__private_variable
def tess(self):
print('class1tess')
__tess = tess
class class2(class1):
def __init__(self):
super(class2, self).__init__()
def tess(self):
print('class2tess')
__tess=tess
if __name__ == '__main__':
'''以下证明保护变量和保护方法能在本类和子类中被引用,无法被自动推荐出来,但是可以手写出来'''
class1()._protect_method()
class2()._protect_method()
print(class1()._protected_variable)
print(class2()._protected_variable)
'''以下验证私有变量和私有方法在本类和子类中的引用情况,实际是改名了而已。注意自己类内引用自己类内的私有方法和属性,不需要改名引用'''
print(class1()._class1__private_variable)
print(class2()._class1__private_variable)
class1()._class1__tess()
class2()._class1__tess()
class2()._class2__tess()
运行结果如下:
E:\Python\Python38\python.exe D:/pythonprojects/python-auto-test/test/test20240130.py
_protect method
_protect method
5
5
6
6
class1tess
class1tess
class2tess
进程已结束,退出代码0
总结一下,头部只带一个下划线的变量,在本类和其他类都可以引用,但是其他类无法联想推荐出变量。头部带两个下划线的变量,在本类内可以直接引用,在其他类内,只能引用类似于_class__tess的形式,且无法联想推荐出变量