字符串转换成变量的几种方法

网络找了好久终于找到字符串转换成变量的几种方法

转自:http://blog.chinaunix.net/uid-20393955-id-345573.html

var = “This is a string”
varName = ‘var’
s= locals()[varName]
s2=vars()[varName]

print s
print s2
print eval(varName)

 

————————————————————————–

最近在Django的views中使用了该方法,发现这些转换成变量的方法有一定的作用域

我在models中定义了一个数据库名称,而且有数据

class bxtp_p(models.Model):
    name = models.CharField(max_length=30)
    patch = models.CharField(max_length=1000)
    patchtime = models.DateTimeField(auto_now=False)
    owner = models.CharField(max_length=30)
    subject = models.CharField(max_length=100)
    status = models.CharField(max_length=50)
    track = models.CharField(max_length=500)
    available = models.NullBooleanField(default=True)
    category = models.CharField(max_length=15,default='',choices=CHOICE)
    comments = models.CharField(max_length=200, default='')
    def __unicode__(self):
        return self.name
    def shortpatch(self):
        return re.findall(r'/(\d+)',self.patch)[0]
    def fullpatch(self):
        return 'https://android.intel.com/#/c/%s/' % re.findall(r'/(\d+)',self.patch)[0]

views代码如下

传入的project为 ‘p’

from people.models import *
import people
def index_page(request, project):
    global timefrom
    global timeto
    index_html = 'index_{0}.html'.format(project)
    bxtps = locals()[('bxtp_' + project)]

 

url代码如下:

urlpatterns = [
    url(r'^patch/(.+)/$', people_views.index_page),

但是在浏览器输入 

http://xx.xx.xx.xx:8000/patch/p/ 时报错

但是我在views中调用时一直提示 KeyError: u’bxtp_p’ 不存在

project====: p
Internal Server Error: /patch/p/
Traceback (most recent call last):
  File “/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py”, line 41, in inner
    response = get_response(request)
  File “/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py”, line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File “/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py”, line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File “/home/yu/workspace/cp0_code/cp0/people/views.py”, line 44, in index_page
    bxtps = locals()[(‘bxtp_’ + project)]
KeyError: u’bxtp_p’

后来直接引用数据库的__dict__方法解决

def index_page(request, project):
    global timefrom
    global timeto
    index_html = 'index_{0}.html'.format(project)
    bxtps = people.models.__dict__['bxtp_' + project]

(备注:调用locals()方法出来的结果和__dict__不一样,也就是第一次字典里面没有‘bxtp_p’这个key)

所以要理解locals()用法:

locals() 函数会以字典类型返回当前位置的全部局部变量

注意是局部变量,所以要慎用

    原文作者:不良小白
    原文地址: https://blog.csdn.net/lyx20120714/article/details/82344881
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞