On reading and writing permissions of Python object data _python

Source: Internet
Author: User

Object-oriented programming languages tend to be more convenient and secure than the process-oriented language when writing large programs. One of the reasons is: class mechanism.

Class, a large number of data classification, encapsulation, so that a data object into a complete individual, close to the real life, highly abstract. However, Python's encapsulation of classes is not good, because all properties and methods are public, you can access or write at will, you can modify the properties of the class outside the class, and even add attributes. This is really disturbing.

Here is a summary of the study after the solution.

1, use the 2 underscore prefix to hide the attribute or method.

__xxx

#!/usr/bin/python3
#-*-coding:utf-8-*-


class Student:
  def __init__ (self,name,score):
    Self.name = name
    Self.__score = score #将score隐藏起来 so that it is only available within the class.

  def __show (self):    #一个隐藏的方法, also only internally available
    print (Self.name,self.__score) #使用被隐藏的属性__score
    
  def show ( Self):
    self.__show ()    #注意被隐藏方法的调用方式.


  
def main (): He
  = Student (' Bob ', a) he
  . Show ()       #显示: Bob
  #print (he.__score)   #AttributeError: ' Student ' object has no attribute ' __score '
  #he. __show ()      #AttributeError: ' Student ' object has no attribute ' __show '

  #隐藏属性真的被隐藏了吗? In fact, you can still use the format obj._classname__attributename
  #但是仅仅作为了解, do not recommend the use of hidden properties.
  print (He._student__show ())  #显示: Bob
  print (He._student__score)   # Show:
  
  
  

if __name__== "_ _MAIN__ ":
  Main ()

The effect of a double underline on a class property:

1. Make the property available only to the interior of this class, neither external nor subclass can read the modification directly.

2. The properties of the class using _ _ are changed by the name when implemented, such as __age in the class will eventually become _a__age (name reorganization), which is typically used in parent classes that involve inheritance. This avoids quilt class attribute overrides.

2. Create manageable properties.

Sometimes we need to do an extra check on a property's write, deny write to an illegal value, throw an exception.

#!/usr/bin/python3
#-*-coding:utf-8-*-


class Student:
  def __init__ (self,name,score):
    self.name = Name
    Self.score = score 

  @property        #实现属性的读取方法, when reading the score value of the instance, this function
  def score (self) is called:
    return Self.__score

  
  @score. Setter     #实现属性写入方法, when writing the score property of an instance, call this function
  def score (self,newval):
    if not Isinstance (newval, (int,float)):
      raise TypeError (' score value must be a number ')
    if newval>100 or newval <0:
      raise ValueError (' score value must between 0 and ')

    Self.__score = newval

  

  
def main (): He
  = S Tudent (' Bob ')
  he.score =   #重新写入 

  
  print (he.score)  #读取   
    
  

if __name__== "__main__":
  Main ()

We can see that Self.__score is where the value of the property is actually stored, and the Self.score is a function (just like a property), which is the way to get and write the property value.

The Socre.setter decorated function is also invoked when initializing, because a Self.score call appears under the __init__ () function

Since Self.__score is only used to refer to the value of a property, can you name it with something else? such as Savescore ..... Of course it is, but it is "exposed" and we do not want it to be available externally, or should

Add __ to hide it and prevent accidental modification.

Sometimes, you are sure that a class does not involve inheritance, then you can rewrite the double underline as a single down line, although it will not achieve a hidden effect, but: on the one hand, this does not trigger a name reorganization mechanism,

To avoid a fuss, the other side, with an underscore beginning, can remind the user that this attribute should not be used directly. Then, it is by consciousness.

An instance object can add properties to the outside arbitrarily.

#!/usr/bin/python3
#-*-coding:utf-8-*-


class Student:
  def __init__ (self,name,score):
    self.name = Name
    Self.score = Score 

 

  
def main (): He
  = Student (' Bob ')
  he.age =
  print (he.age)
  

if __ name__== "__main__":
  Main ()

using __slots__



#!/usr/bin/python3
#-*-coding:utf-8


class Student:
  __slots__ = (' name ', ' score ') #将属性名以字符串形式加入元组
  def __init__ (self,name,score):
    self.name = name
    Self.score = Score 

 

  
def main (): He
  = Student (' Bob ',
  he.age =  #AttributeError: ' Student ' object has no attribute ' age '
  print (he.age)
  

if __name__== "__main__":
  Main ()

In this way, the object's properties are limited to the inside of the class.

But __slots__ cannot be inherited. Moreover, __slots__ 's design was not intended to be used above, but rather to optimize memory usage when creating a large number of (million) objects.

Summarize:

As it was written, I realized that the above technique was of little significance. The design of the class is the programmer himself, the user is himself, then, the object properties of the

Read and write on their own grasp, class design itself does not need too much protection code, otherwise it will be very bloated, and reduce efficiency. Protection should take place outside the class, allowing the data to be accepted by the class object to be always legitimate, which is more lightweight and flexible. This is how I feel.

This article on the Python object data read and Write permission is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.

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.