convert a string to a variable
bruceg113355 at gmail.com
bruceg113355 at gmail.com
Thu May 24 18:54:11 EDT 2018
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?
Thanks,
Bruce
# Tested on Python 3.6.5
# Case 1: This works
indata = 'animal_tiger'
vars()[indata] = "Tigers, big and strong!"
print (animal_tiger)
# Case 2: This works
class animal():
def create (self, indata):
vars(self)[indata] = "Tigers, big and strong!"
print (self.animal_tiger)
tmp = animal()
tmp.create('animal_tiger')
#############################################################
# Case 3: This does not work
indata = 'animal.tiger'
vars()[indata] = "Tigers, big and strong!"
print (animal.tiger)
#Case 4: This does not work
class animal():
def create (self, indata):
vars(self)[indata] = "Tigers, big and strong!"
print (self.animal.tiger)
tmp = animal()
tmp.create('animal.tiger')
More information about the Python-list
mailing list