1.1   访问控制

1.1.1   外部代码修改实例的属性

>>> daidai = Student('DAIDAI', 99)

>>> daidai.score

99

>>> daidai.score = 99 + 1    --修改score属性

>>> daidai.score

100

1.1.2   外部代码访问实例属性限制

>>> 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))

...

>>> daidai = Student('DAIDAI', 99)

>>> daidai.__name

Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

AttributeError: 'Student' object has noattribute '__name'

Python中,实例的变量名如果以__开头,就变成了一个私有变量private),只有内部可以访问,外部不能访问。当然,此时外部代码肯定不能修改内部实例的属性。

此时修改属性变量需调用方法

>>> class Student(object):

...    def __init__(self, name,score):

...        self.__name = name

...        self.__score = score

...     def set_name(self, name):

...         self.__name = name

...     def set_score(self, score):

...         self.__score = score

...    def print_score(self):

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

...

>>>

>>>

>>> daidai = Student('DAIDAI', 99)

>>> daidai.print_score()

DAIDAI: 99

>>> daidai.set_name('xiongxiong')

>>> daidai.print_score()

xiongxiong: 99

获取实例的变量属性需通过方法

class Student(object):

   ...

 

   def get_name(self):

       return self.__name

 

   def get_score(self):

       return self.__score

调用方法修改变量属性时,参数检查

>>> class Student(object):

...    def __init__(self, name,score):

...        self.__name = name

...        self.__score = score

...    def set_name(self, name):

...        self.__name = name

...    def set_score(self, score):

...        if 0 <= score <= 100:     --参数检查控制部分

...             self.__score = score

...         else:

...             raise ValueError('bad score')

...    def print_score(self):

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

...

>>>

>>> daidai = Student('DAIDAI', 99)

>>> daidai.print_score()

DAIDAI: 99

>>> daidai.set_score(-1)

Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

 File "<stdin>", line 11, in set_score

ValueError: bad score

注意:

__xxx__         特殊变量,可以访问

__xxx           私有变量,不可访问

_xxx                        可以访问,不推荐这样写

>>> class Student(object):

...    def __init__(self, name,score):

...        self._name = name

...        self._score = score

...    def set_name(self, name):

...        self.__name = name

...    def set_score(self, score):

...        if 0 <= score <= 100:

...             self.__score = score

...        else:

...             raise ValueError('bad score')

...    def print_score(self):

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

...

>>>

>>>

>>> daidai = Student('DAIDAI', 99)

>>> daidai._name

'DAIDAI'