Python 3:将字符串转换为变量 [英] Python 3: Convert String to variable

查看:153
本文介绍了Python 3:将字符串转换为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从.txt文件中读取文本,并且需要使用读取的数据之一作为类实例的变量。

I am reading text from a .txt file and need to use one of the data I read as a variable for a class instance.

    class Sports:
        def __init__(self,players=0,location='',name=''):
            self.players = players
            self.location = location
            self.name = name
        def __str__(self):
            return  str(self.name) + "is played with " + str(self.players) + " players per team on a/an " + self.location + "."

    def makeList(filename):
        """
        filename -- string
        """
        sportsList = []
        myInputFile = open(filename,'r')
        for line in myInputFile:
            record = myInputFile.readline()
            datalist = record.split()
            sportsList.append(datalist[0])
            datalist[0] = Sports(int(datalist[1]),datalist[2],datalist[3])        
        myInputFile.close()
        print(football.players)

    makeList('num7.txt')

我需要转换数据列表[0]是一个变量名称的字符串(基本上没有引号),因此可以用来创建该名称的实例。

I need to convert datalist[0], which is a string, to a variable name (basically without the quotes) so it can be used to create an instance of that name.

推荐答案

在开始之前,我必须说创建这样的变量是一种非常糟糕的(并且可能是危险的)编码实践。太多的事情可能出错,并且很容易丢失您自发创建的名称。而且,这样的代码很难维护。

Before I begin, I must say that creating variables like that is a very bad (and potentially hazardous) coding practice. So much can go wrong and it is very easy to lose track of the names you spontaneously create. Also, code like that is terrible to maintain.

但是,对于在蓝色月亮中您必须必须创建变量的情况一个字符串,您可以执行以下操作:

However, for the once in a blue moon scenario where you must create a variable out of a string, you may do something like this:

>>> a="b"
>>> exec(a+"=1")
>>> print(b)
1
>>>

因此,在您的代码中,您可以执行以下操作:

So, in your code, you could do something to the effect of:

exec(datalist[0]+"= Sports(int(datalist[1]),datalist[2],datalist[3])")

再次,这是一个非常棘手的解决方案,不应99%地使用。但是,出于1%完全不正常的情况,我想证明它是可以完成的。

Once again, this is a very hackish solution that should not be used 99% of the time. But, for the sake of the 1% completely abnormal scenario, I wanted to show that it can be done.

这篇关于Python 3:将字符串转换为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆