Nathan Burt
Nathan Burt

Reputation: 3

How to get attributes from an object using a variable as object name

What I want to do is randomly choose an item in a list, and then use that to pull through the attributes of that object. I can obviously hard code the current_target variable (Creature.Dog.attr1 for example) but I would ideally like this to be generated.

My code goes like this:

class Creature(object):

    def __init__(self, name, attr1, attr2):
        self.name = name
        self.attr1 = attr1
        self.attr2 = attr2


Squirrel = Creature("Squirrel", 20, 1)
Dog = Creature("Dog", 50, 10)
Goblin = Creature("Goblin", 100, 100)

creature_list = ['Squirrel', 'Dog', 'Goblin']

def get_creature():
    return random.choice(creature_list)

These are called from my main class:

current_target = Creature.get_creature()
print("The current target is %s, and has %s, and %s"  
     % (current_target, Creature.current_target.attr1, Creature.current_target.attr2))

Upvotes: 0

Views: 57

Answers (2)

Vikas Ojha
Vikas Ojha

Reputation: 6950

class Creature(object):

    def __init__(self, name, attr1, attr2):
        self.name = name
        self.attr1 = attr1
        self.attr2 = attr2

Squirrel = Creature("Squirrel", 20, 1)
Dog = Creature("Dog", 50, 10)
Goblin = Creature("Goblin", 100, 100)

creature_list = [Squirrel, Dog, Goblin]

def get_creature():
    return random.choice(creature_list)
current_target = get_creature()
print("The current target is %s, and has %s, and %s"
 % (current_target.name, current_target.attr1, current_target.attr2))

Upvotes: 1

Graeme Stuart
Graeme Stuart

Reputation: 6053

Use instances not strings

A simple change is to put your Creature instances in the list and choose from there.

import random

class Creature(object):

    def __init__(self, name, attr1, attr2):
        self.name = name
        self.attr1 = attr1
        self.attr2 = attr2


Squirrel = Creature("Squirrel", 20, 1)
Dog = Creature("Dog", 50, 10)
Goblin = Creature("Goblin", 100, 100)

creature_list = [Squirrel, Dog, Goblin]

def get_creature():
    return random.choice(creature_list)

current_target = get_creature()
print("The current target is %s, and has %s, and %s"
     % (current_target.name, current_target.attr1, current_target.attr2))

Upvotes: 1

Related Questions