convert a string to a variable
brucegoodstein at gmail.com
brucegoodstein at gmail.com
Fri May 25 09:44:05 EDT 2018
On Friday, May 25, 2018 at 1:56:14 AM UTC-4, dieter wrote:
> bruceg113355 at gmail.com writes:
>
> > 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?
> > ...
> > # Case 3: This does not work
> > indata = 'animal.tiger'
> > vars()[indata] = "Tigers, big and strong!"
> > print (animal.tiger)
>
> In the expression "animal.tiger", the "variable" is "animal",
> not "animal.tiger". It is evaluated as follows:
> determine the object bound to "animal", access its attribute "tiger".
> Your error message tells you that the first step (object bound
> to "animal") has been successful, but the result lacks the
> attribute "tiger".
>
> > #Case 4: This does not work
> > class animal():
> > def create (self, indata):
> > vars(self)[indata] = "Tigers, big and strong!"
>
> Here you want to define the attribute "tiger" (I think),
> not "animal.tiger". Note that the "." in a Python expression
> (not a string) separates two individual steps: determine
> an object corresponding to the leftside to the "."; access
> the attribute corresponding to the name following the ".".
> > print (self.animal.tiger)
> >
> > tmp = animal()
> > tmp.create('animal.tiger')
Hi Dieter,
After reading your response, I picked up on the 'attribute' word.
Updated case 3: (Success)
indata = 'tiger'
setattr (animal, indata, "Tigers, big and strong!!!")
print (animal.tiger)
animal.tiger = "Lions are bigger and stronger"
print (animal.tiger)
Output is:
Tigers, big and strong!!!
Lions are bigger and stronger
I am still working on case 4 using setattr.
Thanks,
Bruce
More information about the Python-list
mailing list