Python Object-Oriented programming--access restrictions

Source: Internet
Author: User

< objects with no access restrictions >

Inside class, you can have properties and methods, and external code can manipulate the data by invoking the instance variable directly, thus hiding the complex logic inside. However, from the definition of the previous student class (see: Python Object-oriented programming-class definitions and objects), External code is also free to modify an instance's name , score properties :

>>> bart = Student(‘Bart Simpson‘, 98)>>> bart.score98>>> bart.score = 59>>> bart.score59

< increase access Restrictions >

to make the internal property inaccessible externally , add the nameof the property to the two underscore " __" , in Python, if the variable name of the instance starts with", __" it becomes a private variable (private)that can only be accessed internally and cannot be accessed externally, so we change the student class to:

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

after the change , for external code, there is no change, but it has been unable to access from outside 实例变量.__name and 实例变量.__score :

>>> bart = Student(‘Bart Simpson‘, 98)>>> bart.__nameTraceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: ‘Student‘ object has no attribute ‘__name‘

This ensures that external code cannot arbitrarily modify the state inside the object, so that the code is more robust through access-restricted protection. but if the external code wants to get the property name and score, you can add get_name the Student class and the get_score Such a method :

class Student(object):    ...    def get_name(self):        return self.__name    def get_score(self):        return self.__score

If you want to allow external code to modify the property score again, you can add a method to the student class set_score :

class Student(object):    ...    def set_score(self, score):        self.__score = score

The original kind of direct pass bart.score = 59 can also modify the properties, so the great effort to define the method to modify the properties of the purpose is to pass the parameters, you can check the parameters , Avoid passing arguments that are not valid:

class Student(object):    ...    def set_score(self, score):        if 0 <= score <= 100:            self.__score = score        else:            raise ValueError(‘bad score‘)

? Note     

    In Python, the variable name is similar to __xxx __ , that is, double underscore start , and with Double underline end , is a special variable , special variables are directly accessible , is not a private variable , so you cannot use __name__ __ SCORE__ A variable name such as .

There are times when you see an instance variable name that starts with a single underscore , such as an _name instance variable that can be accessed externally , but, in accordance with the rules , when you see such a variable, It means, " although I can be accessed, but please treat me as a private variable, do not feel free to access".

Principles of < access restrictions >

Double underline startThe instance variableis not necessarily not accessible from outside,cannot be accessed directly__name的原因is because the Python interpreter __name The _Student__name variable is changed into , so, can still be passed_Student__nameto access__namevariables:

>>> bart._Student__name‘Bart Simpson‘

All in all, Python itself has no mechanism to stop you from doing bad things, all on your own. Finally, note the following error notation:

>>> bart = Student(‘Bart Simpson‘, 98)>>> bart.get_name()‘Bart Simpson‘>>> bart.__name = ‘New Name‘ # 设置__name变量!>>> bart.__name‘New Name‘

on the surface , the external code " succeeds" in setting the __name variable , but actually this __name variables and the inside of class __nameThe variable is not a variable ! of internal__namethe variable has been automatically changed by the Python interpreter._Student__name, while the external code givesbarthas added a__namevariable. Try not to believe:

>>> bart.get_name() # get_name()内部返回self.__name‘Bart Simpson‘

<wiz_tmp_tag id= "Wiz-table-range-border" contenteditable= "false" style= "Display:none;" >



From for notes (Wiz)



Python Object-Oriented programming--access restrictions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.