Discuss / Python / 外部代码可以修改啊

外部代码可以修改啊

Topic source

古而树里

#1 Created at ... [Delete] [Delete and Lock User]

我发现外部代码虽然不能访问,但是可以修改设定访问限制的内部变量,比如:

# -*- coding: utf-8 -*-
"""
Created on Thu Jan  7 16:55:19 2016

@author: tedoreve
"""
' a test module '

class Student(object):

    def __init__(self, name, score):
        self.__name = name
        self.__score = score

    def print_score(self):
        print('%s: %s' % (self.__name, self.__score))

    def get_grade(self):
        if self.__score >= 90:
            print('A')
        elif self.__score >= 60:
            print('B')
        else:
            print('C')

bart = Student('Bart Simpson', 59)
lisa = Student('Lisa Simpson', 87)
bart.print_score()
lisa.print_score()
bart.get_grade()
lisa.get_grade()

bart.__name=1
print(bart.__name)

bart.__name 输出是1

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

你写个:

class Student(object):

    def __init__(self, name, score):
        self.__name = name
        self.__score = score

    def print_name(self):
        return self.__name

然后看看print_name()打印的内容

古而树里

#3 Created at ... [Delete] [Delete and Lock User]

啊,我懂了

这里的bart.__name其实是外部变量,值为1

您说的bart.__name是在类中的内部变量,不会受到外部代码改变

谢谢

廖雪峰

#4 Created at ... [Delete] [Delete and Lock User]

真正的原因是Python解释器在执行class定义时自动把所有__name改成了__Student_name,这样你在外部写的__name和定义的__name就不会冲突。

用dir(bart)查看所有实例变量看看


  • 1

Reply