Python: Function Data encapsulation

Source: Internet
Author: User

Data encapsulation

An important feature of object-oriented programming is data encapsulation. In the above Student class, each instance has its own name and score this data. We can access this data through functions, such as printing a student's score:

def Print_score (STD):      ... Print ('%s:%s' % (std.name, Std.score) ... >>>59

However, since the Student instance itself has this data, to access the data, there is no need to go from outside the function to access, you can directly within the Student class to define the function to access the data, so that the "data" to encapsulate it. The functions of these encapsulated data are Student associated with the class itself, and we call it the method of the class:

class Student (object):     def __init__ (self, Name, score):         = name        = score    def  Print_score (self):        Print ('%s:%s' % (Self.name, Self.score))

To define a method, except for the first argument self , the other is the same as the normal function. To invoke a method, just call it directly on the instance variable, except that self it does not pass, and other parameters are passed in normally:

>>>59

In this way, we look at the class from the outside, just need to Student know that the creation of the instance needs to give name and score , and how to print, are Student defined inside the class, the data and logic is "encapsulated", the call is easy, but do not know the details of the internal implementation.

Another benefit of encapsulation is the ability to Student add new methods to the class, such as get_grade :

 class   Student (object): ...  def   Get_grade (self):  if  self.score >= 90:  return  "  a   " elif  self.score >= 60:  return   " b  "  else  :  return  "  c   " 
Restrict access

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 previous definition of the student class, the external code is free to modify the properties of an instance name score :

>>> Bart = Student ('Bart Simpson', ')>>> Bart.score 59>>> Bart.score = 99>>> bart.score99

If you want the internal properties to be inaccessible externally, you can add the name of the property with two underscores __ , and in Python, the variable name of the instance __ becomes a private variable (private), which can only be accessed internally and cannot be accessed externally, so We changed the Student class:

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', ')>>> Bart. __name Traceback (most recent):   " <stdin> "  in <module>'Student'__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 what if external code gets name and score? You can add to the student class get_name and get_score this method:

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 score? You can add additional methods to the student class set_score :

class Student (object):    ...     def Set_score (self, score): Self        . __score = Score

You may ask, the original kind of direct through bart.score = 99 can also be modified Ah, why to define a method big trouble? because in a method, you can check the parameters to avoid passing in invalid arguments!!! :

class Student (object):    ...     def Set_score (self, score):         if 0 <= score <=: Self            . __score = score        else:            raise valueerror (' Bad score')

python special variable __xxxx___: It is important to note that in Python, the variable name is similar, which starts with a double underscore and ends with a double underscore, which is __xxx__ a special variable that can be accessed directly, not a private variable. Therefore, you cannot __name__ use __score__ a variable name like this.

python-contracted private variable _xxxx: Sometimes you see an instance variable name that starts with an underscore, such as an _name instance variable that can be accessed externally, but, by convention, 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 ".

python private variable __xxxx begins with: is an instance variable starting with a double underscore not necessarily externally accessible? Actually, it's not. cannot be accessed directly __name because the Python interpreter has changed the variable to the outside __name _Student__name , so you can still _Student__name access the __name variable by:

>>> bart._student__name'Bart Simpson'

However, it is strongly recommended that you do not do this because different versions of the Python interpreter may __name change to different variable names.

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   ", 59)  >>> Bart.get_name ()  "  bart Simpson   " >>> Bart. __name  =  "  New Name   " #   set the __name variable!  >>> Bart. __name   " new Name   " 

on the surface, the external code "succeeds" in setting the __name variable, but actually the variable __name and the variable inside the class are __name not a variable! the internal __name variables have been automatically changed by the Python interpreter _Student__name , and the external code bart adds a new __name variable. Try not to believe:

# get_name () internal return self.__name ' Bart Simpson '

Python: Function Data encapsulation

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.