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