Python 学习笔记 -- 类的访问限制

#在Python中其实并没有像C++一样的,private,public,protected这些关键字用来限制访问权限
#但是我们可以在属性和方法的前面加上__双下划先
class testClass(object):

    def __init__(self):
        self.__name = "欧米茄"
        self.score = 100

    def __print_score(self):
        print(self.score)

    def print_name(self):
        print(self.__name)


test = testClass()
print("没有加双下划线的score:",test.score)
try:
    test.__name
except:
    print("虽然看上去像是实现访问权限限制,但是其实没有!")
    print("它的真实名字其实是test._testClass__name : ",test._testClass__name)

print("没有加双下划线的print_name:")
test.print_name()
try:
    test.__print_score()
except:
    print("同理,其实它只是改了个名字,真实名字test._testClass__print_score")
    test._testClass__print_score()   

#真正的名字其实就是_类名__XXXXXX
原文地址:https://www.cnblogs.com/jiangchenxi/p/8053603.html