Set the variable access permission in Python.

Source: Internet
Author: User

Set the variable access permission in Python.

In the Class, attributes and methods can be available, while external code can directly call the method of instance variables to operate data, thus hiding the internal complex logic.

However, from the definition of the Student class, external code can still freely modify the name and score attributes of an instance:

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

If you want to prevent internal properties from being accessed externally, you can add two underlines __before the attribute name. In Python, if the instance variable name starts, it becomes a private variable, which can only be accessed internally and cannot be accessed externally. Therefore, we change the Student class to the following:

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 modification, there is no change to the external code, but the instance variables. _ name and instance variables. _ score cannot be accessed from the External:

>>> 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 the external code cannot modify the internal state of the object at will, so that the code is more robust through access restriction protection.

But what if the external code needs to get the name and score? You can add the get_name and get_score methods to the Student class:

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

What if I want to allow external code to modify the score? You can add the set_score Method to the Student class:

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

You may ask, why do you need to define a method that can be modified directly through bart. score = 59? In the method, you can check the parameters to avoid passing invalid parameters:

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

In Python, the variable name is similar to _ xxx _, which starts with a double underline and ends with a double underline. It is a special variable, special variables can be directly accessed, rather than private variables. Therefore, variable names such as _ name _ and _ score _ cannot be used.

Sometimes, you will see instance variable names starting with an underscore, such as _ name, which can be accessed outside the instance variable. However, according to conventions, when you see such a variable, it means, "Although I can be accessed, please think of me as a private variable and do not access it at will ".

Do instance variables starting with double underscores (_) cannot be accessed from outside? Not actually. You cannot directly access _ name because the Python interpreter has changed the _ name variable to _ Student _ name. Therefore, you can still access the _ name variable through _ Student _ name:

>>> bart._Student__name'Bart Simpson'

However, we strongly recommend that you do not do this because different versions of Python interpreters may change _ name to different variable names.

In general, Python itself does not have any mechanism to prevent you from doing bad things, and it is all dependent on self-consciousness.

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.