Python dynamic load variable sample sharing _python

Source: Internet
Author: User

As we all know, after the program is started, each program file will be loaded into memory, so if the program text changes again, the current program does not affect the operation of the program is a protection.

However, for languages like python that interpret execution, we sometimes use the form "from module import variable name", if the variable is directly defined in the file, the variables are defined and assigned at the beginning of the program, and the values are unchanged during the run. If the module is intended to be overridden during the run, the changed value of the variable cannot be used.

For this problem, you can change the idea that the variables in this module are defined in the function, and the function is executed dynamically when the program is running, so that you can get the latest value of the variable. Here is an example:

First, do not use a function:

Copy Code code as follows:

#model1. py
P_hello = ' Hello world! '

#test1. py
From Model1 import P_hello
File = open (' model1.py ', ' W ')
File.write ("P_hello = '%s! '"% (' Hello you))
File.close ()
Print P_hello

Thus, when executing test1.py, the result is still ' Hello World ', not ' hello you ', indicating that the variable has been loaded into memory, although the module's file has been rewritten on the hard disk.

Next, use the case of the function:

Copy Code code as follows:

#model1. py
def rule ():
P_hello = ' Hello world! '
Return locals ()

#test1. py
From model1 Import rule
File = open (' model1.py ', ' W ')
File.write (' Def rule (): \ n ')
File.write ("P_hello = '%s! ') \ n "% (' Hello you '))
File.write ("return locals () \ n")
File.close ()
P_hello = Rule () [' P_hello ']
Print P_hello

In this way, the result of print is Hello, because at the time of running, the function is executed first, then the variable is obtained by the function, and the new value is obtained.

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.