[Reserved] Python dynamically generated variables

Python loop created with a plurality of variables, such as creating a1 =, a2 =, a3 =, a4 =, a5 = or self.a1 =, self.a2 =, self.a3 =

I. built-in functions can be accomplished by the locals python

locals is a python's built-in functions, he may be the dictionary way to access local and global variables.
python which records the variable name with a space, like a window javascript, like he recorded with a variety of global variables.
Each module, each function has its own namespace, a record of variables, constants, class names and values.

Like JS like when in use python variables will be to search the following steps:
1, or a class of local variables.
2, the global variable.
3, built-in variables.
The above three steps, which look step to find the corresponding variable, it will not look down. If you can not find in these three steps, it will throw an exception.

 

Python can also be dynamically generated javascript variables like that. We see a dynamically generated javascript variables:

1 var obj = {}; 
2 for (var i = 0, len = 10; i <len; i ++) { 
3 obj [ 'a' + i] = i; 
4} 
5 
6 console.log (i); // { 'a0': 0, 'a1': 1 ...., 'a9': 9}

The Python locals  Method

1 createVar = locals()
2 listTemp = range(1,10)
3 for i,s in enumerate(listTemp):
4     createVar['a'+i] = s
5 print a1,a2,a3
6 #......
Copy the code
DEF foo. 1 (args): 
2 = X. 1 
. 3 Print about locals () 
. 4 
. 5 foo (123) 
. 6 
. 7 will be # { 'arg': 123, ' x': 1}
Copy the code
1 for i in range(3):
2     locals()['a'+str(i)]=i
3     print 'a'+str(i)

Print Results: variable name: a0 a1 a2 corresponding values ​​a0 = 0 a1 = 1 a2 = 2

 

2. For each class, recommended setattr () method

setattr object is added to property or method

 

setattr( object, name, value)

This is the counterpart of getattr(). The arguments
are an object, a string and an arbitrary value. The string may name an existing
attribute or a new attribute. The function assigns the value to the attribute,
provided the object allows it. For example, setattr(x,
'foobar', 123)
 is equivalent to
x.foobar = 123.

 

Copy the code
Test class. 1 (Object): 
2 DEF the __init __ (Self): 
. 3 DIC = { 'A': 'AA', 'B': 'BB'} 
. 4 in dic.keys for I (): 
. 5 setattr (Self, I , dic [i]) # the first parameter is the object, there is actually Self test. the second parameter is the variable name, and the third value of the variable 
. 6 Print (self.a) 
. 7 Print (self.b,) 
. 8 t = test ()
Copy the code

Print result: aa, bb

 Print self dynamic variables:

1 exec("self.a"+str(i)+".move("+str(x)+","+str(y)+")")
2 exec("self.a"+str(i)+".show()")

 

 

Tip: Create a dynamic dictionary will bring additional expenses, if you can, please try to specify key-value pairs.

Guess you like

Origin www.cnblogs.com/jfdwd/p/11129958.html