没有什么是不能访问的

class Student():
    sum = 0

    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.__score = 0 # 表示实例下有score这么一个变量

    def marking(self,score):
        if score < 0:
            print("不能给别人打负分")
            __score = 0
        else:    
            self.__score = score
            print(self.name+"这次考试考了"+ str(self.__score) + "分")

    def do_math_homework(self):
        pass

    def do_english_homework(self):
        pass

s1 = Student("安琪拉",12)
# s1.marking(50)
# s1.marking(-1) 
s1.__score = -12
print(s1.__score)
-12

不是已经设置了私有吗,为什么还能访问??

s1.__score = -12 # 这里的__score是新增的属性
print(s1.__score)
class Student():
    sum = 0

    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.__score = 0 # 表示实例下有score这么一个变量

    def marking(self,score):
        if score < 0:
            print("不能给别人打负分")
            __score = 0
        else:    
            self.__score = score
            print(self.name+"这次考试考了"+ str(self.__score) + "分")

    def do_math_homework(self):
        pass

    def do_english_homework(self):
        pass

s1 = Student("安琪拉",12)
s2 = Student("蒙犽",13)
# s1.marking(50)
# s1.marking(-1) 
s1.__score = -12 # 会被动态添加到__dict__列表中
print(s1.__score)
print(s1._Student__score)
print(s2._Student__score)
print(s1.__dict__)
print(s2.__dict__)
print(s2.__score)
-12
0
0
{'name': '安琪拉', 'age': 12, '_Student__score': 0, '__score': -12}
{'name': '蒙犽', 'age': 13, '_Student__score': 0}
Traceback (most recent call last):
  File "/Users/scottxiong/Desktop/end/python/class/c11.py", line 33, in <module>
    print(s2.__score)
AttributeError: 'Student' object has no attribute '__score'

python对私有变量的保护机制,__score已经被改名了_Student__score

通过下面这个方式还是可以读取到私有变量的,可以看到python并不能阻止悲剧的发生

print(s2._Student__score)

results matching ""

    No results matching ""