一. 访问限制:
1. 定义
在Class内部,可以有属性和方法,而外部的代码可以通过直接调用实例变量的方法来操作数据。但是这种操作方法有很大的弊端:外部的代码可以自由修改实例中的属性
class Student(object):
def __init__(self,name,age):
self.name = name
self.age = age
def getScore(self,score):
print('The student score is %.2f' %score)
student = Student('xiaoming',55)
print(student.age)
student.age = 66
print(student.age)
这种情况下很不安全,因此很多时候我们要让内部属性不被外部访问,可以在属性的名称前加上两个下划线__,在python中,实例的变量名以__开头就变成一个私有变量(private),只有内部可以访问,外部不可以访问。
class Student(object):
def __init__(self,name,age):
self.__name = name
self.__age = age
def getScore(self,score):
print('The student score is %.2f' %score)
student = Student('xiaoming'