2

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.

DSM
  • 342,061
  • 65
  • 592
  • 494
user1763846
  • 21
  • 1
  • 2
  • 3
    What do you think this'll get you? If you want to refer to the instance later, you're either going to have to introduce hacky dereferencing or you're going to have to store the instance in some structure to operate on like a dictionary anyway. And in that case why not just use a dictionary with the "name" as the key instead? – DSM Oct 21 '12 at 21:54
  • Another problem here is calling readline() when you already have the line (that you don't use). This will cause records to be skipped. – Keith Oct 21 '12 at 22:17
  • Risky thing - dynamic variable names. Why don't you just use dictionary? – volcano Oct 21 '12 at 23:25
  • Don't create variables dynamically, you (essentially) never want to do this. Just use a *container*, like a `list` or a `dict` object. – juanpa.arrivillaga Apr 01 '19 at 19:14

1 Answers1

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.