zoukankan      html  css  js  c++  java
  • Python 动态生成多个变量

    引用自:https://blog.csdn.net/u013061183/article/details/78015673

    用Python循环创建多个变量, 如创建 a1=   、a2=   、a3=   、a4=   、a5=    或  self.a1=    、self.a2=   、 self.a3=

    一. 可以通过python的内置函数locals 来完成

    locals是python的内置函数,他可以以字典的方式去访问局部和全局变量。
    python里面用名字空间记录着变量,就像javascript的window一样,他记录着各种全局变量。
    每个模块,每个函数都有自己的名字空间,记录着变量,常量,类的命名和值。

    就像JS一样,当python在使用变量时,会按照下面的步骤去搜索:
    1、函数或类的局部变量。
    2、全局变量。
    3、内置变量。
    以上三个步骤,其中一下步骤找到对应的变量,就不会再往下找。如果在这三个步骤都找不到,就会抛出异常。

    Python 也可以像javascript那样动态生成变量。我们看javascript的动态生成变量:

    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}

    Python中的locals 方法

    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 #......
    复制代码
    1 def foo(args):
    2     x=1
    3     print locals()
    4 
    5 foo(123)
    6 
    7 #将会得到 {'arg':123,'x':1}
    复制代码
    1 for i in range(3):
    2     locals()['a'+str(i)]=i
    3     print 'a'+str(i)

    打印结果:变量名:  a0  a1   a2   对应值  a0=0    a1=1    a2=2

    二、使用eval

    a = [1,2,3,4]
    for i in a:
    b = "a%s = 0"% (i)
    exec b
    eval("a%s" % i)
    print a1
    print a2
    print a3

    三. 对于class,推荐使用setattr()方法

    setattr给对象添加属性或者方法

    复制代码
    1 class test(object) :
    2     def __init__(self):
    3         dic={'a':'aa','b':'bb'}
    4         for i in dic.keys() :
    5             setattr(self,i,dic[i]) #第一个参数是对象,这里的self其实就是test.第二个参数是变量名,第三个是变量值
    6         print(self.a)
    7         print(self.b)
    8 t=test()
    复制代码

    打印结果: aa  ,   bb

     动态打印self变量:

    1 exec("self.a"+str(i)+".move("+str(x)+","+str(y)+")")
    2 exec("self.a"+str(i)+".show()")
  • 相关阅读:
    关于 Profile
    empty
    Vim Editor
    C++ Note
    Android NDK Sample
    Dealing with the ! when you import android project
    File attributes and Authority of Linux
    Java与C的相互调用
    The source code list of Android Git project
    Enable Android progurad in the case of multiple JAR lib
  • 原文地址:https://www.cnblogs.com/Presley-lpc/p/9153865.html
Copyright © 2011-2022 走看看