Python 3: Convert String to variable [duplicate]

2019-08-14 05:42发布

问题:

This question already has an answer here:

  • How do I create a variable number of variables? 15 answers

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')

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.

回答1:

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])")

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.