公有变量直接访问
>>> 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))
...
>>> ll = Student('lilu',99)
>>> ll
<__main__.Student object at 0x0000000000A3C550>
>>> ll.name
'lilu'
>>> ll.score
99
私有变量无法直接访问,可以用特殊方法调用(变量前加上双下划线)
>>> 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))
...
>>> lm = Student('lime',66)
>>> lm
<__main__.Student object at 0x0000000000A3C7F0>
>>> lm.score
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Student' object has no attribute 'score'
>>> lm.name
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Student' object has no attribute 'name'
>>> '''不能直接访问__name是因为Python解释器对外把__name变量改成了_Student__name,所以,仍然可以通过_Student__name来访问__name变量'''
>>> lm._Student__name
'lime'
>>> lm._Student__score
66
可以通过内置函数,调用内置函数来修改变量值
>>> 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_score(self):
... return self.__score
... def get_name(self):
... return self.__name
... def set_score(self,score):
... self.__score = score
... def set_name(self,name):
... self.__name = name
>>> zyt = Student('zhaoyouting',98)
>>> zyt.get_name()
'zhaoyouting'
>>> zyt.get_score()
98
>>> lgx =Student('linggengxin',88)
>>> lgx.set_score(99)
>>> lgx.get_score()
99
>>> lgx.set_name('LINGGENGXIN')
>>> lgx.get_name()
'LINGGENGXIN'