Talking about private variables in Python, talking about python private

Source: Internet
Author: User

Talking about private variables in Python, talking about python private

Private Variable Representation

A private variable is added with two underscores before the variable.

Class Teacher (): def _ init _ (self, name, level): self. _ name = name self. _ level = level # obtain the instructor's level def get_level (self): return self. _ level # obtain the name def get_in_name (self): return self. _ name

The dynamic method cannot read private variables.

Even a dynamic method cannot read private variables, and an error is returned when the private variables are forcibly read.

# Define the dynamic method def get_name (self): return self. _ name # dynamic method value assignment Teacher. get_name = get_namet = Teacher ("GG", 5) print ("level is:", t. get_level () # feasible print ("name is", t. get_name () # An error is returned, indicating that this attribute is not available.

Private variables cannot be modified in dynamic methods.

Dynamic methods cannot modify private variables. If you force the modification, no error is reported, but the modification is ineffective.

T. set_name ("NN") # print (t. get_in_name () is not effective, but print (t. get_in_name () is not reported. # obtain the name inside the class and output the GG

Forcibly read and modify private variables

What should we do if we forcibly read and change private variables?

There is an unrecommended but feasible method:

The private property is named "class name_property name" inside the object ".

In this example, it is as follows:

Print ("name is", t. _ Teacher _ name) # output GGt. _ Teacher _ name = "AA" # The print ("name is", t. _ Teacher _ name) # output AA

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.