bruceg113...@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') -- https://mail.python.org/mailman/listinfo/python-list