-7

In the following code:

class species:
    def __init__(self, continent):
        self.continent=continent

giraffe = species("africa")

animal = "giraffe"

EDIT: animal is a string

can i retrieve "africa" from var "animal"?

Jala015
  • 73
  • 2
  • 9
  • **animal.continent** is the reference you need. Please look up these details in a tutorial on classes and objects. – Prune Mar 31 '17 at 19:35
  • Possible duplicate of [Python: access class variables via instance](http://stackoverflow.com/questions/10313471/python-access-class-variables-via-instance) – Jamie Counsell Mar 31 '17 at 19:36

2 Answers2

0

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
aghast
  • 14,785
  • 3
  • 24
  • 56
-1

Access the attribute

animal.continent

Naib
  • 999
  • 7
  • 20