convert a string to a variable

Ned Batchelder ned at nedbatchelder.com
Fri May 25 10:07:50 EDT 2018


On 5/25/18 9:52 AM, brucegoodstein at gmail.com wrote:
> On Friday, May 25, 2018 at 8:06:31 AM UTC-4, Ned Batchelder wrote:
>> On 5/24/18 6:54 PM, bruceg113355 at gmail.com wrote:
>>> I am trying to convert a string to a variable.
>>>
>>> I got cases 1 & 2 to work, but not cases 3 & 4.
>>>
>>> The print statement in cases 3 & 4 reports the following:
>>>       builtins.AttributeError: type object 'animal' has no attribute 'tiger'
>>>       
>>> I am stuck on creating variables that can be accessed as follows.
>>>             animal.tiger
>>>             self.animal.tiger
>>>
>>> Any suggestions?
>>>
>>>
>> Usually when people want to turn strings into variables, the best answer
>> is to not make variables, but instead have a dictionary.
>>
>> But I don't know what you are going to do with "animal.tiger", so I'm
>> not sure the best answer.  Can you say more about the whole problem?
>>
>> --Ned.
>
> Hi Ned,
>
> I am writing a small interpreter just for fun.
> My program reads and processes text from a file.
> Good or bad, I prefer the variable syntax.

If your own code will never use these variable names, then all of your 
accesses, both reading and writing, will be through these awkward 
mechanisms, I think?  Wouldn't it be easier to use your own dictionary?

--Ned.



More information about the Python-list mailing list