9.1.1, private variable, private method, 9.1.1 private variable method

Source: Internet
Author: User

9.1.1, private variable, private method, 9.1.1 private variable method
Private variable, private method:

  • Python is privatized to plan private attributes and avoid unrelated access! I have a wife. You cannot know who my wife is. You only need to ask me, that is, my private attributes are only known to me]
  • To define private variables and private methods in python, you only need to add the underscore "_" before the variable name or function name.
  • Self. _ variable name or function name used in internal methods of the class.
  • In fact, if you really want to access private variables and private methods, you can also access them, because the private operation actually only changes the variable or function name:
    • In the following example, the value of private_value is changed to _ A _ private_value [that is, _ class name__ attribute name]. However, we do not recommend that you use this method for private access.
    Class A: _ private = 6 _ private_value = 5 def _ private_func (self): print ("hello") def get_private_value (self): return self. _ private_valuea = A () # print (. _ private_value) ### error. The print (. get_private_value () print (. _ A _ private_value)
  • Inheritance of private variables and Methods: [subclass does not inherit the private attributes of the base class, but it is still obtained through the function of the base class or can be forcibly accessed]
Class A: _ private = 6 _ private_value = 5 def _ private_func (self): print ("hello") def get_private_value (self): return self. _ private_valueclass B (A): passb = B () # print (B. _ private_value) # print (B. get_private_value () # You can use the parent class method to obtain the private property print (B. _ A _ private_value) # mandatory access is acceptable.

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.