[Solved] Python class information from variable


Yes. Both animal and giraffe are references to the same underlying object. Very much like “Jala015” and “Jala Smith” and “mom” (or dad?) might all be references to the same person.

Similarly, if you change the continent of the object via one of the references, that change will be visible through the other reference, since they both point to the same place.

Update

Now you say that animal is not a reference to an object, but a string. There are a couple of ways to do that, all of them somewhat complex.

First, if giraffe is a global (as shown in your code, it is) then it will be in the globals() dictionary. You can do this:

giraffe = species('Africa')
animal = "giraffe"

continent = globals()[animal].continent

If giraffe is not global, but rather a local variable in a function, that won’t work. You might be able to get it with locals() but even that is iffy. In that case, and in general, you should probably put this stuff in your own dictionary for lookups:

Zoo = {}  # empty dictionary

giraffe = species('Africa')

Zoo['giraffe'] = giraffe

animal = "giraffe"

continent = Zoo[animal].continent

You can make this simpler by storing the species name in the Animal class, thus:

class Animal:
    def __init__(self, name, where):
        self.name = name
        self.continent = where

Then you could put your objects into a deque, dict, list, set, tuple, or whatever other thing you like, and still match them by brute force:

Zoo = [ Animal('giraffe', 'Africa'), Animal('zebra', 'Africa'), Animal('Cheeto-Stained Ferret-Wearing Shitgibbon', 'North America') ]

pet = None

for animal in Zoo:
    if animal.name == 'giraffe':
        pet = animal
        break

3

solved Python class information from variable