0

Ok so I have the class variable "name", which is random by a list of names,

class Man(object):
  def __init__(self, name, age)
      self.name = "dylan"
      self.age = 4

Now I want to call age, by "dylan"

So I want to do "dylan".age, basically.

How can I do this? Call a variable of a class by its Value?

3 Answers 3

1

It looks to me like "name" is an instance variable not a class variable. If that's so, there's no way to access it unless you already have a reference to the instance "dylan".

Could you make a dictionary to store references to all the instances you create? men["dylan"] = Man("dylan", 42)?

Then you can write men["dylan"].age with any luck!

Sign up to request clarification or add additional context in comments.

Comments

1

This will only work if each name is unique.

First create two accessor methods in your object class that return age and name.

def get_name(self):
    return self.name

def get_age(self):
    return self.age

Then, create a method using a for loop that iterates through each object in your list. Call for the object name, compare it to the name you're looking for, and if it matches return the age.

def find_age_of(sought_name):
    for obj in obj_list:
        if (obj.get_name().lower() == sought_name.lower()):    #'.lower' negates case differences
            return sought_age = obj.get_age()

Finally, call this method using the name as a parameter:

sought_name = 'dylan'
sought_age = find_age_of(sought_name)

1 Comment

thank you, that was very well written, however I think creating a dictionary as Steve Pitchers suggested might be a better idea for my purposes. :)
-1

Make a getter that returns the age

getAge
{
    return self.age;
}

1 Comment

I want to call it outside the class, f.ex if i have. man1 = Man("dylan", 2) and i want to call "2" by typing "dylan"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.