Read and write permissions for python Object Data

Source: Internet
Author: User
The following is an article about the read and write permissions of python object data. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the object-oriented programming language. when writing large programs, it is more convenient and secure than the process-oriented language. One of the reasons is: Class mechanism.

Class, which classifies and encapsulates a large number of data, so that a data object becomes a complete individual, which is close to real life and highly abstract. However, python does not encapsulate classes well, because all attributes and methods are public and you can access or write them at will. you can modify the class attributes outside the class, or even add attributes. This is indeed disturbing.

Next we will summarize the solutions after learning.

1. use two underline prefixes to hide attributes or methods.

_ Xxx #! /Usr/bin/python3 #-*-coding: UTF-8-*-class Student: def _ init _ (self, name, score): self. name = name self. _ score = score # hide the score so that it is only available within the class. Def _ show (self): # A hidden method, which can only be used internally. name, self. _ score) # use the hidden attribute _ score def Show (self): self. _ show () # note the call method of the hidden method. Def main (): he = Student ('Bob', 95) he. show () # Show: Bob 95 # print (he. _ score) # AttributeError: 'Student 'object has no attribute' _ score '# he. _ show () # AttributeError: 'Student 'object has no attribute' _ show '# is the hidden property actually hidden? The format obj. _ className _ attributeName # is still available, but it is only used for understanding. We do not recommend using hidden attributes. Print (he. _ Student _ show () # Display: Bob 95 print (he. _ Student _ score) # Display: 95 if _ name __= = "_ main _": main ()

Effect of double underscores on class attributes:

1. make the attribute used only inside the class, and neither the external nor the subclass can directly read and modify it.

2. when using the _ class attribute, the name will be changed during implementation. for example, the _ age in the class will be changed to _ A _ age (name rename), which has the following advantages: it is usually used in parent classes that involve inheritance. This avoids overwriting quilt attributes.

2. create manageable properties.

Sometimes we need to perform additional checks on attribute writing, and reject writing of invalid values, causing an exception.

#! /Usr/bin/python3 #-*-coding: UTF-8-*-class Student: def _ init _ (self, name, score): self. name = name self. score = score @ property # read the attribute. when you read the score value of an instance, this function def score (self): return self is called. _ score @ score. setter # implements the attribute writing method. when writing the score attribute of an instance, this function def score (self, newVal): if not isinstance (newVal, (int, float) is called )): raise TypeError ('score value must be a number') if newVal> 100 or newVal <0: raise ValueError ('score value must between 0 and 100 ') self. _ score = newVal def main (): he = Student ('Bob', 95) he. score = 100 # re-write print (he. score) # read if _ name __= = "_ main _": main ()

We can find that: self. _ score is the real storage of attribute values, while self. score is a function (but it is used as an attribute). It is a method for obtaining and writing attribute values.

The socret. setter function is also called during initialization, because self. score is called Under The _ init _ () function.

Since self. _ score is only used to reference the attribute value, can it be named differently? For example, saveScore... is acceptable, but it is "exposed" and we do not want to make it available externally.

Add _ to hide it to prevent accidental modification.

Sometimes, if you are sure that a class does not involve inheritance, you can rewrite the double underline as a single slide. although it does not play a hidden role, on the one hand, this will not trigger the name rename mechanism,

The other side should start with an underscore to remind users that this attribute should not be used directly. Then, this depends on self-consciousness.

An instance object can add attributes externally.

#! /Usr/bin/python3 #-*-coding: UTF-8-*-class Student: def _ init _ (self, name, score): self. name = name self. score = score def main (): he = Student ('Bob', 95) he. age = 19 print (he. age) if _ name __= = "_ main _": main () use _ slots __#! /Usr/bin/python3 #-*-coding: UTF-8-*-class Student: _ slots _ = ('name', 'Score ') # add the attribute name as a string to the def _ init _ (self, name, score): self. name = name self. score = score def main (): he = Student ('Bob', 95) he. age = 19 # AttributeError: 'Student 'object has no attribute 'age' print (he. age) if _ name __= = "_ main _": main ()

In this way, the attributes of the object are limited to the class.

However, _ slots _ cannot be inherited. In addition, the design of __slots _ is not intended to use the above method, but to optimize the memory usage when creating a large number of objects.

Summary:

I found that the above technique is of little significance. The design of the class is the programmer himself and the user himself, so the object attribute

Read and write should be controlled by yourself. class design does not require much protection code, otherwise it will be bloated and the efficiency will be reduced. Protection measures should occur outside the class, so that the data received by the class object will always be legal, which is more lightweight and flexible. This is my feeling.

The above discussion about the read and write permissions of python object data is all the content shared by the editor. I hope to give you a reference and support for PHP.

For more information about the read and write permissions of python Object Data, refer to PHP Chinese network!

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.